This answer has the following way to download a file using the node-fetch library https://stackoverflow.com/a/51302466:
const downloadFile = (async (url, path) => {
const res = await fetch(url);
const fileStream = fs.createWriteStream(path);
await new Promise((resolve, reject) => {
res.body.pipe(fileStream);
res.body.on("error", reject);
fileStream.on("finish", resolve);
});
});
How to mock this if a function has this method as part of it? I'm running into weird problems:
unit.test.js
import { PassThrough } from 'stream';
import { createWriteStream, WriteStream } from 'fs';
import fetch, { Response } from 'node-fetch';
import mocked = jest.mocked;
jest.mock('node-fetch');
jest.mock('fs');
describe('downloadfile', () => {
const mockedFetch = fetch as jest.MockedFunction<typeof fetch>;
const response = Promise.resolve({
ok: true,
status: 200,
body: {
pipe: jest.fn(),
on: jest.fn(),
},
});
const mockWriteable = new PassThrough();
mocked(createWriteStream).mockReturnValueOnce(mockWriteable as unknown as WriteStream);
mockedFetch.mockImplementation(() => response as unknown as Promise<Response>);
it('should work', async () => {
await downloadfile();
}),
);
});
Throws:
Cannot read property 'length' of undefined
TypeError: Cannot read property 'length' of undefined
at GlobSync.Object.<anonymous>.GlobSync._readdirEntries (//node_modules/glob/sync.js:300:33)
at GlobSync.Object.<anonymous>.GlobSync._readdir (//node_modules/glob/sync.js:288:17)
at GlobSync.Object.<anonymous>.GlobSync._processReaddir (//node_modules/glob/sync.js:137:22)
at GlobSync.Object.<anonymous>.GlobSync._process (/api/node_modules/glob/sync.js:132:10)
What could the solutions be?