ค้นหาเว็บไซต์

node.js - การทดสอบ Jest - กรุณาเพิ่ม 'import "reflect-metadata"' ที่ด้านบนของจุดเริ่มต้นของคุณ


ฉันกำลังพัฒนาแอปพลิเคชันโดยใช้การฉีดพึ่งพาด้วย tsyringe นี่คือตัวอย่างของเซอร์วิสที่รับ repository เป็นการพึ่งพา:

import { injectable, inject } from 'tsyringe'

import IAuthorsRepository from '@domains/authors/interfaces/IAuthorsRepository'

@injectable()
export default class ListAuthorsService {
  constructor (
    @inject('AuthorsRepository')
    private authorsRepository: IAuthorsRepository
  ) {}

และคอนเทนเนอร์ของ dependencies:

import { container } from 'tsyringe'

import IAuthorsRepository from '@domains/authors/interfaces/IAuthorsRepository'
import AuthorsRepository from '@domains/authors/infra/typeorm/repositories/AuthorsRepository'

container.registerSingleton<IAuthorsRepository>(
  'AuthorsRepository',
  AuthorsRepository
)

export default container

ในการทดสอบ ผมไม่ต้องการใช้การพึ่งพาที่ลงทะเบียนบนคอนเทนเนอร์ แต่แทนที่จะส่งอินสแตนซ์จำลองผ่านพารามิเตอร์

let authorsRepository: AuthorsRepositoryMock
let listAuthorsService: ListAuthorsService

describe('List Authors', () => {
  beforeEach(() => {
    authorsRepository = new AuthorsRepositoryMock()
    listAuthorsService = new ListAuthorsService(authorsRepository)
  })

แต่ฉันได้รับข้อผิดพลาดดังต่อไปนี้:

tsyringe ต้องการ reflect polyfill กรุณาเพิ่ม 'import "reflect-metadata"' ไว้ที่ส่วนบนของจุดเข้าโปรแกรมของคุณ

สิ่งที่ฉันคิดคือ - "ฉันอาจจำเป็นต้องนำเข้าแพ็กเกจ reflect-metadata ก่อนการรันการทดสอบ" ดังนั้นฉันจึงสร้าง jest.setup.ts ซึ่งนำเข้าแพ็กเกจ reflect-metadata แต่เกิดข้อผิดพลาดอื่นขึ้น:

อินสแตนซ์ของรีโพซิทอรีไม่ถูกกำหนดบางประการ

ฉันอยากจะทำการทดสอบของฉันอย่างสงบ

คำตอบ #1

ก่อนอื่นสร้างไฟล์ jest.setup.ts ในโฟลเดอร์รากของโปรเจกต์ของคุณ

ใน jest.config.js ของคุณ ให้ค้นหาบรรทัดนี้:

// A list of paths to modules that run some code to configure or set up the testing framework before each test
// setupFilesAfterEnv: [],

ยกเลิกการคอมเมนต์ และเพิ่มเส้นทางไฟล์ jest.setup.ts ของคุณ

// A list of paths to modules that run some code to configure or set up the testing framework before each test
setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],

ตอนนี้นำเข้า reflect-metadata ใน jest.setup.ts:

import 'reflect-metadata';

และทำการทดสอบอีกครั้ง

บทความที่เกี่ยวข้อง