我正在用tsyringe开发一个使用依赖注入的应用程序。这是将存储库作为依赖项接收的服务的示例:
import { injectable, inject } from 'tsyringe'
import IAuthorsRepository from '@domains/authors/interfaces/IAuthorsRepository'
@injectable()
export default class ListAuthorsService {
constructor (
@inject('AuthorsRepository')
private authorsRepository: IAuthorsRepository
) {}以及依赖容器:
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)
})但我收到了以下错误:
注射器需要一个反射填充。请将“导入”反映元数据“”添加到入口点的顶部。
我想的是--“在执行测试之前,我可能需要导入反射元数据包”。因此,我创建了一个导入jest.setup.ts包的reflect-metadata。但又发生了另一个错误:

存储库的实例在某种程度上没有定义。
我想平静地做我的测试。
发布于 2021-05-03 14:51:39
首先,在项目的根中创建一个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'],现在,在jest.setup.ts中导入反射元数据。
import 'reflect-metadata';再做一次测试。
发布于 2021-04-03 17:49:05
我在这里经历了同样的问题,并重构了测试,发现它必须先导入依赖项,然后导入将要测试的服务类。
https://stackoverflow.com/questions/65233200
复制相似问题