Search code examples
typescriptjestjsnestjs

Please make sure that the argument ContactRepository at index [0] is available in the RootTestModule context


I'm trying to test a class via Nest. In this class (cf image below), the person who coded the class, create a repository via typeorm.

enter image description here

When I try to test the "createContact" function I get the following error : "Nest can't resolve dependencies of the ContactService (?). Please make sure that the argument ContactRepository at index [0] is available in the AuthModule context".

This is my test class :

enter image description here

Do you know how to make the test take this into account and therefore not get the error anymore?


Solution

  • You need to provide an implementation for the value to be injected for @InjectRepository(Contact). Fortunately, Nest provides a way to get what that injection token is using getRepositoryToken(). With this, you can make a custom provider to provide the token and the mock that is going to be used in the actual implementation's place. The test setup would look something like this:

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

    You can provide anything you want for save and find, but doing this allows you to also check what's passed to the mock, and how many times they were called (if you're watching the mocks that is).

    You can find many more examples here