Search code examples
nestjse2e-testingnestjs-testing

Override provider in single test in nest.js e2e testing


I have e2e test of module with controller and some providers:

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();
  });

I'm mocking here database connection by mocking TestEntity repository and it's working fine - real implementation of service gets mocked database query result. However in one single test I need to TestEntity provider use mock find function with different implementation:

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

How can I achieve that? I want to use real implementation of TestService which under the hood uses TestEntity repository which is mocked (and I don't want to use test database). Thank you in advance for help.


Solution

  • Ok I've found it, I'll post answer here just for record, in case anyone would have similiar problem, because it isn't described in Nest docs (or I couldn't find it).

    When you create testing module and instance of application from testing module, application object have resolve method which can be used to retrieve provider:

    it('/test', async () => {
        const testRepository = await app.resolve(getRepositoryToken(TestEvent));
    
        testRepository.find = jest.fn(() => []);
    
        return request(<...>).expect(<...>);
      });