如何在同一个 class 中模拟一个方法 我正在 nestjs/jest 中测试
How to mock a method in the same class I'm testing in nestjs/jest
我在 NestJS 中有一项服务,我正在使用 Typescript 中的 @nestjs/testing
进行测试。但是其中一种方法依赖于另一种方法,我只想为一个测试模拟依赖方法,所以我不能使用 ES6 class 模拟,因为那会覆盖 class 我'我用模拟测试。
class UsersService {
findMany(ids) {
return ids.map(id => this.findOne(id));
}
findOne(id) {
return this.httpService.get(id);
}
}
我想测试这两种方法,但我只想在测试 findMany
.
时模拟 findOne
提前致谢。
您想在这里进行间谍活动。在本文档中查找 '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"])
});
我在 NestJS 中有一项服务,我正在使用 Typescript 中的 @nestjs/testing
进行测试。但是其中一种方法依赖于另一种方法,我只想为一个测试模拟依赖方法,所以我不能使用 ES6 class 模拟,因为那会覆盖 class 我'我用模拟测试。
class UsersService {
findMany(ids) {
return ids.map(id => this.findOne(id));
}
findOne(id) {
return this.httpService.get(id);
}
}
我想测试这两种方法,但我只想在测试 findMany
.
时模拟 findOne
提前致谢。
您想在这里进行间谍活动。在本文档中查找 '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"])
});