theboyonfire
theboyonfire

Reputation: 595

Mock Injected Service In Unit Testing Nest.js

I would like to test my service (Location Service). In this Location Service, I inject repository and other service called GeoLocationService, but got stuck when I am trying to mock this GeoLocationService.

It throws me an error

GeolocationService › should be defined

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

Here is the provider's code

@Injectable()
export class LocationService {
  constructor(
    @Inject('LOCATION_REPOSITORY')
    private locationRepository: Repository<Location>,

    private geolocationService: GeolocationService, // this is actually what I ma trying to mock
  ) {}

  async getAllLocations(): Promise<Object> {
return await this.locationRepository.find()
  }
....
}

Here is the test code

describe('LocationService', () => {
  let service: LocationService;
  let repo: Repository<Location>;

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      imports: [GeolocationModule],
      providers: [
        LocationService,
        {
          provide: getRepositoryToken(Location),
          useClass: Repository,
        },
      ],
    }).compile();

    service = module.get<LocationService>(LocationService);
    repo = module.get<Repository<Location>>(getRepositoryToken(Location));
  });

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

Upvotes: 11

Views: 24908

Answers (1)

Jay McDoniel
Jay McDoniel

Reputation: 70111

Instead of adding imports: [GeolocationModule] you should provide a mock of GeolocationService. This mock should have the same method names as the GeolocationService, but they can all be stubbed (jest.fn()) or they can have some return values (jest.fn().mockResolved/ReturnedValue()). Generally, the custom provider (added to the providers array) would look like this:

{
  provide: GeolocationService,
  useValue: {
    method1: jest.fn(),
    method2: jest.fn(),
  }
}

You can find a large sample of mocks in this repository.

Upvotes: 19

Related Questions