SpyOn a mocked jest module not spying properly
Suggestion 1
Maybe spyOn and module mocks don't play well together. You could try using a jest.fn()
directly inside the module mock like so
jest.mock('file-saver', ()=>{ return { saveAs: jest.fn((blob, filename) => { return filename; }) }});
and then
expect(FileSaver.saveAs).toBeCalled()
Remember to call jest.clearAllMocks()
or similar between tests.
Suggestion 2I've had issues with jest.mock working in unexpected ways with the jest module cache, especially when working with singleton imports. Maybe you have this issue. if file-saver
and dom-to-image
don't have any state initialized or side-effects on import time you should be able to swap jest.mock
out for overrides of the functions you need to mock.
beforeEach(() => { FileSaver.saveAs = jest.fn(...); domtoimage.toBlob = jest.fn(...);})
So for those of you wondering something similar...my issue (as I suspected) was the promise in domtoimage.toBlob(node, {filter: filter}).then()
essentially, the promise was resolving after my expect was called.
in order to solve it, I placed my expect
behind a setTimeout, thus forcing it to fire after the promise is resolved.
DownloadImage('x', 'name'); //small timeout to resolve the promise inside downldimage function setTimeout(()=>{ expect(FileSaver.saveAs).toHaveBeenCalledWith('myblob', fileName); done(); }, 100);