Jest URL.createObjectURL 不是函数 [英] Jest URL.createObjectURL is not a function
问题描述
我正在开发一个 reactJs 应用程序.我正在使用 jest 来测试我的应用程序.我想测试一个下载 blob 的函数.
I'm developping a reactJs application. I'm using jest to test my application. I want to test a function that download a blob.
但不幸的是我收到了这个错误:
But unfortunately I receve this error:
URL.createObjectURL 不是函数
URL.createObjectURL is not a function
我的测试功能:
describe('download', () => {
const documentIntial = { content: 'aaa' };
it('msSaveOrOpenBlob should not have been called when navigao is undefined', () => {
window.navigator.msSaveOrOpenBlob = null;
download(documentIntial);
expect(window.navigator.msSaveOrOpenBlob).toHaveBeenCalledTimes(0);
});
});
我要测试的功能:
export const download = document => {
const blob = new Blob([base64ToArrayBuffer(document.content)], {
type: 'application/pdf',
});
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(blob);
return;
}
const fileURL = URL.createObjectURL(blob);
window.open(fileURL);
};
推荐答案
这看起来就像在 Jest 中在 Global 上设置 URL
一样简单.类似的东西
This would appear to be as simple as setting up URL
on the Global in Jest. Something like
describe('download', () => {
const documentIntial = { content: 'aaa' };
global.URL.createObjectURL = jest.fn();
it('msSaveOrOpenBlob should not have been called when navigao is undefined', () => {
global.URL.createObjectURL = jest.fn(() => 'details');
window.navigator.msSaveOrOpenBlob = jest.fn(() => 'details');
download(documentIntial);
expect(window.navigator.msSaveOrOpenBlob).toHaveBeenCalledTimes(1);
});
});
这应该会产生一个测试,您也可以使用该测试来检查是否调用了 global.URL.createObjectURL
.附带说明:您也可能会遇到与 window.open
类似的问题,如果出现这种情况,我建议您也模拟一下.
This should result in a test that you can also use for checking if global.URL.createObjectURL
was called. As a side note: you may also run into a similar issue with window.open
I would suggest mocking that as well if this becomes the case.
这篇关于Jest URL.createObjectURL 不是函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!