代码之家  ›  专栏  ›  技术社区  ›  Verdouze

请确保索引[0]处的参数ContactRepository在RootTestModule上下文中可用

  •  0
  • Verdouze  · 技术社区  · 5 年前

    我想通过Nest测试一个类。在这个类(下面的cf图)中,编写类的人通过typeorm创建了一个存储库。

    enter image description here

    当我尝试测试“createContact”函数时,我得到以下错误:“Nest不能解析ContactService的依赖项(?)。请确保索引[0]处的参数ContactRepository在AuthModule上下文中可用”。

    enter image description here

    你知道如何让测试考虑到这一点,从而不再得到错误了吗?

    0 回复  |  直到 5 年前
        1
  •  1
  •   Jay McDoniel    5 年前

    您需要为要注入的值提供一个实现 @InjectRepository(Contact) . 幸运的是,Nest提供了一种获取注入令牌所用内容的方法 getRepositoryToken() . 有了它,您可以创建一个定制的提供者来提供将在实际实现中使用的令牌和模拟。测试设置看起来 这样地:

    beforeEach(async () => {
      const module = await Test.createTestingModule({
        providers: [
          ContactService,
          {
            provide: getRepositoryToken(Contact),
            useValue: {
              save: jest.fn().mockResolvedValue(mockContact),
              find: jest.fn().mockResolvedValue([mockContact]),
            },
          },
        ],
      }).compile();
    });
    

    save find

    You can find many more examples here

    推荐文章