2

我对带有控制器和一些提供程序的模块进行了 e2e 测试:

beforeAll(async () => {
    const moduleRef = await Test.createTestingModule({
      controllers: [TestController],
      providers: [
        TestService,
        {
          provide: getRepositoryToken(TestEntity),
          useValue: {
            find: jest.fn(async () => testDatabaseResult),
            save: jest.fn(),
          },
        },
      ],
    }).compile();

    app = moduleRef.createNestApplication();
    app.use(cookieParser());
    app.useGlobalPipes(new ValidationPipe());

    await app.init();
  });

我在这里通过模拟 TestEntity 存储库来模拟数据库连接,它工作正常 - 服务的实际实现得到模拟的数据库查询结果。但是在一个测试中,我需要 TestEntity 提供者使用具有不同实现的模拟查找功能:

find: jest.fn(async () => otherMockedTestDatabaseResult)

我怎样才能做到这一点?我想使用 TestService 的真正实现,它在后台使用被模拟的 TestEntity 存储库(我不想使用测试数据库)。提前感谢您的帮助。

4

2 回答 2

0

好的,我找到了,我将在此处发布答案以供记录,以防有人遇到类似问题,因为 Nest 文档中没有描述(或者我找不到它)。

当您从测试模块创建测试模块和应用程序实例时,应用程序对象具有可用于检索提供者的解析方法:

it('/test', async () => {
    const testRepository = await app.resolve(getRepositoryToken(TestEvent));

    testRepository.find = jest.fn(() => []);

    return request(<...>).expect(<...>);
  });
于 2021-09-10T14:16:59.240 回答
0

const testRepository = moduleRef.get( getRepositoryToken(TestEvent) );

阅读:https ://docs.nestjs.com/fundamentals/testing#testing-utilities

于 2021-09-11T01:00:32.037 回答