the method is simply:
import fs from 'fs';
function getFile(path) {
return new Promise(function(resolve, reject) {
fs.readFile(path, 'utf8', function(err, success) {
if (err) reject(err);
else resolve(success);
});
});
}
it is called from other methods but I need to mock the readFile and I have tried 3 options all giving errors:
attempt one:
it('should get data', async () => {
const spy = jest.spyOn(fs,'readFile')
.........
});
It stops at the line with the error:
Cannot spyOn on a primitive value; undefined given
attempt two:
let readFileCallback;
jest.spyOn(fs, 'readFile').mockImplementation((path, options, callback) => {
readFileCallback = callback;
});
throws implementation error because of the options parameter.
Argument of type '(path: any, options: any, callback: any) => void' is not assignable to parameter of type '(path: string | number | Buffer | URL, callback: (err: ErrnoException, data: Buffer) => void) => void'.
if I remove the options parameter, I get the same error:
Cannot spyOn on a primitive value; undefined given
how can I mock the readFile so it returns some text?