模拟注入服务单元内测试嵌套.js



我想测试我的服务(定位服务(。在这个定位服务中,我注入了存储库和其他名为GeoLocationService的服务,但当我试图模拟这个GeoLocationServices时,它被卡住了。

它给我一个错误

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.

这是提供商的代码

@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()
}
....
}

这是测试代码

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

与其添加imports: [GeolocationModule],不如提供GeolocationService的mock。此mock应具有与GeolocationService相同的方法名,但它们都可以被存根化(jest.fn()(,也可以具有一些返回值(jest.fn().mockResolved/ReturnedValue()(。通常,自定义提供程序(添加到providers阵列中(如下所示:

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

您可以在这个存储库中找到大量的mock样本。

最新更新