In my code, I have a function that utilizes the library jszip to zip folders and files:
// app.ts
const runJszip = async (): Promise<void> => {
const zip = new Jszip();
zip.folder('folder')?.file('file.txt', 'just some text');
zip.file('file.txt', 'just some text');
await zip.generateAsync({ type: 'blob' });
};
To test this function, I decided to spy on the methods folder
and file
. I used the mocking partial strategy along with Jest to handle the default export of the jszip library:
// app.test.ts
import { runJszip } from './app';
const mockFile = jest.fn();
const mockFolder = jest.fn();
const mockJszip = jest.fn().mockImplementation(() => {
return {
folder: mockFolder,
file: mockFile,
};
});
jest.mock('jszip', () => {
return jest.fn().mockImplementation(() => ({
__esModule: true,
default: mockJszip,
}));
});
test('jszip', async () => {
await runJszip();
expect(mockFile).toHaveBeenCalledTimes(2);
expect(mockFolder).toHaveBeenCalledTimes(1);
});
However, I encountered an issue where I could not properly mock the folder
method, resulting in the error message:
Message:
zip.folder is not a function
4 | const zip = new Jszip();
5 |
> 6 | zip.folder('folder')?.file('file.txt', 'just some text');
If anyone has any ideas on how to successfully mock and spy on this method, I would greatly appreciate it.
You can check out a minimal reproducible example here.