NestJs/TypeORM: cannot find repository element after compiling TestingModule

Viewed 18

I am trying to mock a TypeORM repository. My code is as such:

describe('DrawingService', () => {
  let service: DrawingService;
  let repository: MockType<Repository<Drawing>>;
  beforeAll(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [
        DrawingService,
        {
          provide: getRepositoryToken(Drawing, 'document'),
          useFactory: repositoryMockFactory,
        },
      ],
    }).compile();

    service = module.get<DrawingService>(DrawingService);
    repository = module.get(getRepositoryToken(Drawing));
  });

  it('DrawingService is defined', () => {
    expect(service).toBeDefined();
  });
}

When running this, Nest returns the following error that confuses me:

  ● DrawingService › DrawingService is defined

    Nest could not find DrawingRepository element (this provider does not exist in the current context)

      44 |
      45 |     service = module.get<DrawingService>(DrawingService);
    > 46 |     repository = module.get(getRepositoryToken(Drawing));
         |                         ^
      47 |   });
      48 |
      49 |   it('DrawingService is defined', () => {

This couldn't have been caused by me putting the providers inappropriately, otherwise error would have been occurred when the module was compiling. I don't think the cause is the mock factory either, as it is just a simple jest.fn().

What can I do to resolve this?

1 Answers

Well that was really silly of me. The problem was really obvious, in hindsight. At the providers array, I put

{
  provide: getRepositoryToken(Drawing, 'document'),
  useFactory: repositoryMockFactory,
},

But below I assigned repository = module.get(getRepositoryToken(Drawing));, when it should have been repository = module.get(getRepositoryToken(Drawing, 'document'))

Related