首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >开玩笑的测试

开玩笑的测试
EN

Stack Overflow用户
提问于 2020-12-10 10:56:17
回答 2查看 7.7K关注 0票数 9

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

代码语言:javascript
复制
import { injectable, inject } from 'tsyringe'

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

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

以及依赖容器:

代码语言:javascript
复制
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

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

代码语言:javascript
复制
let authorsRepository: AuthorsRepositoryMock
let listAuthorsService: ListAuthorsService

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

但我收到了以下错误:

注射器需要一个反射填充。请将“导入”反映元数据“”添加到入口点的顶部。

我想的是--“在执行测试之前,我可能需要导入反射元数据包”。因此,我创建了一个导入jest.setup.ts包的reflect-metadata。但又发生了另一个错误:

存储库的实例在某种程度上没有定义。

我想平静地做我的测试。

EN

回答 2

Stack Overflow用户

发布于 2021-05-03 14:51:39

首先,在项目的根中创建一个jest.setup.ts

jest.config.js中,搜索以下一行:

代码语言:javascript
复制
// 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文件路径。

代码语言:javascript
复制
// 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中导入反射元数据。

代码语言:javascript
复制
import 'reflect-metadata';

再做一次测试。

票数 21
EN

Stack Overflow用户

发布于 2021-04-03 17:49:05

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65233200

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档