nat*_*ate 7 javascript unit-testing reactjs jestjs
我有简单的服务,我需要使用jest进行单元测试:
代码的关键是:
domtoimage.toBlob(node, {filter: filter})
.then(function (blob) {
FileSaver.saveAs(blob, fileName);
});
Run Code Online (Sandbox Code Playgroud)
我已经编写了我的单元测试模块:
import FileSaver from "file-saver";
import domtoimage from "dom-to-image";
jest.mock('dom-to-image', () => {
return {
toBlob: (arg)=>{
let promise = new Promise((resolve, reject) => {
resolve('myblob')
});
return promise;
}
}
});
jest.mock('file-saver', ()=>{
return {
saveAs: (blob, filename) =>{
return filename;
}
}
});
Run Code Online (Sandbox Code Playgroud)
在我的测试中,我有以下间谍设置
const spy = jest.spyOn(FileSaver, 'saveAs');
并调用我的测试功能.
但是,expect语句:expect(spy).toBeCalled()返回false:
expect(jest.fn()).toBeCalled()
但是,在webstorm中,当我调试单元测试时,我可以清楚地看到我的模拟函数被调用(在函数内部达到了断点).
我错过了什么?
建议1
也许spyOn和模块模拟不能很好地配合使用。您可以尝试jest.fn()像这样直接在模块模拟中使用a
jest.mock('file-saver', ()=>{
return {
saveAs: jest.fn((blob, filename) => {
return filename;
})
}
});
Run Code Online (Sandbox Code Playgroud)
然后
expect(FileSaver.saveAs).toBeCalled()
Run Code Online (Sandbox Code Playgroud)
记住jest.clearAllMocks()在测试之间打电话或类似。
建议2
我在jest.mock的jest模块缓存中以意外方式工作时遇到了问题,尤其是在处理单例导入时。也许你有这个问题。如果file-saver并且dom-to-image没有初始化任何状态或对导入时间有副作用,您应该可以换jest.mock出您需要模拟的功能的替代项。
beforeEach(() => {
FileSaver.saveAs = jest.fn(...);
domtoimage.toBlob = jest.fn(...);
})
Run Code Online (Sandbox Code Playgroud)
因此,对于那些想知道类似问题的人...我的问题(正如我怀疑的那样)是承诺domtoimage.toBlob(node, {filter: filter}).then()
本质上,在我的期望被调用后,承诺就得到了解决。
为了解决这个问题,我将expectsetTimeout 放在后面,从而强制它在承诺解决后触发。
DownloadImage('x', 'name');
//small timeout to resolve the promise inside downldimage function
setTimeout(()=>{
expect(FileSaver.saveAs).toHaveBeenCalledWith('myblob', fileName);
done();
}, 100);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1542 次 |
| 最近记录: |