我在 NestJS 中有一項服務,我正在@nestjs/testingTypescript 中進行測驗。但是其中一種方法依賴于另一種方法,我只想模擬一個測驗的依賴方法,所以我不能使用 ES6 類模擬,因為這會覆寫我用模擬測驗的類。
class UsersService {
findMany(ids) {
return ids.map(id => this.findOne(id));
}
findOne(id) {
return this.httpService.get(id);
}
}
我想測驗這兩種方法,但我只想findOne在測驗時模擬findMany。
提前致謝。
uj5u.com熱心網友回復:
你想在這里使用間諜。在本檔案中查找“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"])
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/414960.html
標籤:
