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 is not a function
my test 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); }); });
The function I want to test:
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); };
createObjectURL() The URL. createObjectURL() static method creates a string containing a URL representing the object given in the parameter. The URL lifetime is tied to the document in the window on which it was created. The new object URL represents the specified File object or Blob object.
createObjectURL is synchronous but it seems to complete almost instantaneously. Also note that calling URL. revokeObjectURL in the image's onload handler breaks "Open image in New Tab" in the image's context menu.
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); }); });
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With