Jest 测试 - 请在入口点的顶部添加“import “reflect-metadata””

Lau*_*ris 5 node.js typescript jestjs tsyringe

我正在开发一个使用依赖注入的应用程序tsyringe。这是接收存储库作为依赖项的服务的示例:

import { injectable, inject } from 'tsyringe'

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

@injectable()
export default class ListAuthorsService {
  constructor (
    @inject('AuthorsRepository')
    private authorsRepository: IAuthorsRepository
  ) {}
Run Code Online (Sandbox Code Playgroud)

和依赖项容器:

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
Run Code Online (Sandbox Code Playgroud)

在测试中,我不想使用在容器上注册的依赖项,而是通过参数传递模拟实例。

let authorsRepository: AuthorsRepositoryMock
let listAuthorsService: ListAuthorsService

describe('List Authors', () => {
  beforeEach(() => {
    authorsRepository = new AuthorsRepositoryMock()
    listAuthorsService = new ListAuthorsService(authorsRepository)
  })
Run Code Online (Sandbox Code Playgroud)

但我收到以下错误:

tsyringe 需要反射 polyfill。请在入口点的顶部添加“import “reflect-metadata””。

我的想法是 - “我可能需要在执行测试之前导入反射元数据包”。所以我创建了一个jest.setup.ts导入reflect-metadata包。但是出现另一个错误:

错误

存储库的实例不知何故未定义。

我想安静地运行我的测试。

小智 32

首先在项目的根目录中创建一个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: [],
Run Code Online (Sandbox Code Playgroud)

取消注释并添加您的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'],
Run Code Online (Sandbox Code Playgroud)

现在将反射元数据导入jest.setup.ts

import 'reflect-metadata';
Run Code Online (Sandbox Code Playgroud)

并再次运行测试。


小智 0

我在这里经历了同样的问题并重构测试发现它必须首先导入依赖项,然后导入将要测试的服务类