I have a function that uses fs.writeFile
as follows:
async function writeToTextFile() {
// processing
writeFile(fileName, data, (error) => {
if (error) {
logger.child({ error });
}
logger.log();
});
};
I want to test the error branch within the error callback of writeFile, but I’m having trouble doing so. This is my unit test currently with jest:
it('should log an error when filesystem writing fails', async () => {
const fs = require('fs');
const mockWriteFile = jest.spyOn(fs, 'writeFile').mockRejectedValue(new Error('testError');
await writeToTextFile();
expect(logger).toHaveBeenCalledWith("testError");
However, I think this is just forcing the function to reject with an error rather than the “real” behavior where it executes the callback function. In other words, my test is failing as expected with
Error: testError
at Object.<anonymous>...
(rest of stack trace)
How can I make it so that writeFile’s callback is tested?
Thanks!