【问题标题】:How to mock a method in the same class I'm testing in nestjs/jest如何在我在 Nestjs/jest 中测试的同一个类中模拟一个方法
【发布时间】:2022-01-17 06:53:11
【问题描述】:
我在 NestJS 中有一项服务,我正在 Typescript 中使用 @nestjs/testing 进行测试。但是其中一种方法依赖于另一种方法,我只想模拟一个测试的依赖方法,所以我不能使用 ES6 类模拟,因为这会覆盖我用模拟测试的类。
class UsersService {
findMany(ids) {
return ids.map(id => this.findOne(id));
}
findOne(id) {
return this.httpService.get(id);
}
}
我想测试这两种方法,但我只想在测试findMany 时模拟findOne。
提前致谢。
【问题讨论】:
标签:
javascript
typescript
unit-testing
jestjs
nestjs
【解决方案1】:
你想在这里使用间谍。在本文档中查找“spyOn”:底部附近的https://docs.nestjs.com/fundamentals/testing。
这是我尝试编写的与您发布的代码相关的示例:
test('findMany', () => {
const spy = new UsersService;
// Here's the key part ... you could replace that "awesome" with something appropriate
jest
.spyOn(spy, 'findOne')
.mockImplementation(() => "awesome");
// Just proving that the mocking worked, you can remove this
expect(spy.findOne()).toBe("awesome");
const ids = ["Dio", "Lemmy"];
expect(spy.findMany(ids)).toStrictEqual(["awesome", "awesome"])
});