Nest.js 单元测试中的模拟注入服务

the*_*ire 10 node.js jestjs nestjs

我想测试我的服务(位置服务)。在此位置服务中,我注入存储库和其他名为 GeoLocationService 的服务,但当我尝试模拟此 GeoLocationService 时陷入困境。

\n

它给我一个错误

\n
GeolocationService \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\n
Run 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\n
Run Code Online (Sandbox Code Playgroud)\n

这是测试代码

\n
describe('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});\n
Run 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)

您可以在此存储库中找到大量模拟示例

  • 当您添加“imports: [SomeModule]”时,如果“SomeModule”有其他导入,您需要注意在测试上下文中也可以使用这些导入,然后是这些导入的导入,依此类推。只需添加服务,您就可以确切地知道需要提供哪些依赖项,并且可以提供基本的模拟,而无需进一步陷入依赖地狱 (4认同)