node.js - 在单元测试 Nest.js 中模拟注入服务
问题描述
我想测试我的服务(定位服务)。在这个位置服务中,我注入了存储库和其他名为 GeoLocationService 的服务,但是当我试图模拟这个 GeoLocationService 时卡住了。
它给我一个错误
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
. 这个模拟应该与 具有相同的方法名称GeolocationService
,但它们都可以被存根(jest.fn()
)或者它们可以有一些返回值(jest.fn().mockResolved/ReturnedValue()
)。通常,自定义提供程序(添加到providers
数组中)如下所示:
{
provide: GeolocationService,
useValue: {
method1: jest.fn(),
method2: jest.fn(),
}
}
推荐阅读
- html - 引导卡对齐不正确
- javascript - 如何删除作为对象一部分的数组中的消息
- php - PHP Laravel Trix 所见即所得如何显示数据库中的内容
- python - 使用 imageio 或 pyautogui 截屏时包含鼠标光标?
- blockchain - 退还所有在solidity合约上输入的地址
- r - 如何在同一张图中绘制“计数”和“身份”
- python - 在 keras ImageDataGenerator.flow() 中使用多输出标签并使用 model.fit_generator()
- nsis - 具有 UNC 路径的 NSIS CopyFiles
- jquery - 点击时传递参数会出错
- android - 使 SpannableStringBuilder 的多个部分加粗