我正在开发一个reactJs应用程序。我正在开玩笑地测试我的应用程序。我想测试下载blob的功能。
但是不幸的是我收到这个错误:
URL.createObjectURL不是函数
我的测试功能:
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); };
这看起来就像URL在Jest中设置Global 一样简单。就像是
URL
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如果出现这种情况,我建议您也嘲笑一下。
global.URL.createObjectURL
window.open