Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest URL.createObjectURL is not a function

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); }; 
like image 680
Melchia Avatar asked Oct 24 '18 12:10

Melchia


People also ask

What is URL createObjectURL?

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.

Is createObjectURL Async URL?

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.


1 Answers

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.

like image 152
None of your Beez Wax Avatar answered Sep 25 '22 08:09

None of your Beez Wax