Nest JS providers mock issue

82 Views Asked by At

I am trying to test my Nest JS service. If I use @InjectRepository(Country) instead of @Inject(REPO_CONSTANTS.country) the test is easy to pass however I am looking for a solution for the existing setup. I am adding a simple example how the setup looks like. I think I am not able to mock the connection provider.

My current code looks like below.

country.module.ts

@Module({
  imports: [DatabaseModule],
  controllers: [CountryController],
  providers: [
    {
      provide: REPO_CONSTANTS.country,
      useFactory: (dataSource: DataSource) => dataSource.getRepository(Country),
      inject: [REPO_CONSTANTS.dataSource],
    },
    ,
    CountryService,
  ],
  exports: [CountryService],
})
export class CountryModule {}

country.service.ts

@Injectable()
export class CountryService {
  constructor(
    @Inject(REPO_CONSTANTS.country)
    private readonly countryRepository: Repository<Country>,
  ) {}

  async findAll(): Promise<Country[]> {
    return await this.countryRepository.find();
  }

  async findOne(id: string): Promise<Country> {
    return await this.countryRepository.findOneBy({ id });
  }
}

country.service.spec.ts

describe('CountryService', () => {
  let service: CountryService;
  let repository: Repository<Country>;
  const mockCountries = [
    {
      id: 'BD',
      title: 'Bangladesh',
      phone: '88',
      timezone: 'Asia/Dhaka',
    },
    {
      id: 'DE',
      title: 'Germany',
      phone: '49',
      timezone: 'Europe/Berlin',
    },
    {
      id: 'MY',
      title: 'Malaysia',
      phone: '60',
      timezone: 'Asia/Kuala_Lumpur',
    },
  ];

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [
        CountryService,
        {
          provide: getRepositoryToken(Country),
          useValue: {
            find: jest.fn().mockResolvedValue(mockCountries),
            findOneBy: jest.fn(),
          },
        },
        // I think this needs to be mocked
        {
          provide: REPO_CONSTANTS.country,
          useFactory: (dataSource: DataSource) => dataSource.getRepository(Country),
          inject: [REPO_CONSTANTS.dataSource],
        },

      ],
    }).compile();

    service = module.get<CountryService>(CountryService);
    repository = module.get(getRepositoryToken(Country));
  });

  it('should be defined', () => {
    expect(service).toBeDefined();
  });

  describe('findAll', () => {
    it('should return all countries', async () => {
      const result = await service.findAll();
      expect(result).toEqual(mockCountries);
    });
  });
});

error

● CountryService › findAll › should return all countries

    Nest can't resolve dependencies of the COUNTRY (?). Please make sure that the argument DATA_SOURCE at index [0] is available in the RootTestModule context.

    Potential solutions:
    - Is RootTestModule a valid NestJS module?
    - If DATA_SOURCE is a provider, is it part of the current RootTestModule?
    - If DATA_SOURCE is exported from a separate @Module, is that module imported within RootTestModule?
      @Module({
        imports: [ /* the Module containing DATA_SOURCE */ ]
      })

      31 |
      32 |   beforeEach(async () => {
    > 33 |     const module: TestingModule = await Test.createTestingModule({
         |                                   ^
      34 |       providers: [
      35 |         CountryService,
      36 |         {
0

There are 0 best solutions below