【发布时间】:2020-07-06 08:44:16
【问题描述】:
当承诺拒绝使用 Jest 时,我正在尝试测试 console.error 输出。我发现在我的测试运行后承诺似乎正在解决,导致测试失败。
示例函数:
export default function doSomething({ getData }) {
const success = data => {
//do stuff with the data
}
const handleError = () => {
//handle the error
}
getData.then(response => success(response)).catch(error => {
console.error(error)
handleError()
})
}
示例测试文件:
import doSomething from "doSomething"
it("should log console.error if the promise is rejected", async () => {
const getData = new Promise((resolve, reject) => {
reject("fail");
});
global.console.error = jest.fn();
await doSomething({ getData });
expect(global.console.error).toHaveBeenCalledWith("fail");
})
//fails with global.console.error has not been called
当我探索这个问题时,我注意到如果我添加一个 console.log 并等待它,它就可以工作。
这会过去的...
import doSomething from "doSomething"
it("should log console.error if the promise is rejected", async () => {
const getData = new Promise((resolve, reject) => {
reject("fail");
});
global.console.error = jest.fn();
await doSomething({ getData });
await console.log("anything here");
expect(global.console.error).toHaveBeenCalledWith("fail");
})
如何正确测试这个?我应该重构getData 函数的调用方式吗?只要调用doSomething 函数,就需要调用它。
【问题讨论】:
标签: javascript promise jestjs