the*_*ire 10 node.js jestjs nestjs
我想测试我的服务(位置服务)。在此位置服务中,我注入存储库和其他名为 GeoLocationService 的服务,但当我尝试模拟此 GeoLocationService 时陷入困境。
\n它给我一个错误
\nGeolocationService \xe2\x80\xba should be defined\n\n Nest can't resolve dependencies of the GeolocationService (?). Please make sure that the argument HttpService at index [0] is available in the RootTestModule context.\n\nRun Code Online (Sandbox Code Playgroud)\n这是提供商的代码
\n@Injectable()\nexport class LocationService {\n constructor(\n @Inject('LOCATION_REPOSITORY')\n private locationRepository: Repository<Location>,\n\n private geolocationService: GeolocationService, // this is actually what I ma trying to mock\n ) {}\n\n async getAllLocations(): Promise<Object> {\nreturn await this.locationRepository.find()\n }\n....\n}\n\nRun Code Online (Sandbox Code Playgroud)\n这是测试代码
\ndescribe('LocationService', () => {\n let service: LocationService;\n let repo: Repository<Location>;\n\n beforeEach(async () => {\n const module: TestingModule = await Test.createTestingModule({\n imports: [GeolocationModule],\n providers: [\n LocationService,\n {\n provide: getRepositoryToken(Location),\n useClass: Repository,\n },\n ],\n }).compile();\n\n service = module.get<LocationService>(LocationService);\n repo = module.get<Repository<Location>>(getRepositoryToken(Location));\n });\n\n it('should be defined', () => {\n expect(service).toBeDefined();\n });\n});\nRun Code Online (Sandbox Code Playgroud)\n
Jay*_*iel 18
imports: [GeolocationModule]您应该提供 的模拟,而不是添加GeolocationService。该模拟应该与 具有相同的方法名称GeolocationService,但它们都可以被存根 ( jest.fn()) 或者它们可以有一些返回值 ( jest.fn().mockResolved/ReturnedValue())。一般来说,自定义提供程序(添加到providers数组中)将如下所示:
{
provide: GeolocationService,
useValue: {
method1: jest.fn(),
method2: jest.fn(),
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
20998 次 |
| 最近记录: |