开玩笑的URL.createObjectURL不是一个函数 [英] Jest URL.createObjectURL is not a function
问题描述
我正在开发一个reactJs应用程序.我正在开玩笑地测试我的应用程序. 我想测试下载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.
这篇关于开玩笑的URL.createObjectURL不是一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!