Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
69
rated 0 times [  73] [ 4]  / answers: 1 / hits: 75854  / 6 Years ago, wed, october 24, 2018, 12:00:00

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);
};

More From » reactjs

 Answers
16

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.


[#53266] Friday, October 19, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
harrisonnelsonb

Total Points: 63
Total Questions: 112
Total Answers: 97

Location: Kazakhstan
Member since Mon, Sep 26, 2022
2 Years ago
;