【发布时间】:2020-12-15 17:39:27
【问题描述】:
如何使用 Jest Test 来测试这个方法:
delayedFetch() {
setTimeout(() => {
this.fetchData();
}, 1000);
我尝试过使用 Async 和 await,但我很可能使用错了。
【问题讨论】:
如何使用 Jest Test 来测试这个方法:
delayedFetch() {
setTimeout(() => {
this.fetchData();
}, 1000);
我尝试过使用 Async 和 await,但我很可能使用错了。
【问题讨论】:
很难测试带有副作用的代码,而且您没有提供完整的上下文,但我会尽力提供帮助。
我认为setTimeout 内的this.fetchData() 中的this 引用了delayedFetch 方法本身。 (我不知道这是你的意图,至于我如何使用 vue.js
但无论如何你都可以在这里找到如何测试 setTimeouts link to jest doc
这是一个简单的实现
const someObj = {
// I assume the delayedFetch is some method of an object
fetchData() {
return "some-data";
},
delayedFetch() {
const vue = this;
setTimeout(() => {
vue.fetchData();
}, 1000);
}
}
jest.useFakeTimers();
test("delayedFetchTest", () => {
someObj.delayedFetch();
expect(setTimeout).toHaveBeenCalledTimes(1);
expect(setTimeout).toHaveBeenLastCalledWith(expect.any(Function), 1000);
})
【讨论】: