I am stucking for 3 hours on this topic. I dont find a solution how to test the if(err) branch in this code:
function createFile(data){
return new Promise(function(resolve, reject) {
try {
if(data === null || data === undefined){
throw new Error(errorMessages.noDataDefined);
}
let internalJobId = uuid.v4();
let fileName = 'project_name' + internalJobId + '.xml';
fs.writeFile(config.tmpPath + fileName, data, function (err) {
if (err){
throw new Error(err.toString());
} else {
resolve(fileName);
}
});
} catch (error) {
return reject(error);
}
});
}
This test passes but it does not call the if (err) { throw new Error(err.toString())}
I have to find a solution, how the callback returns an error, but I dont get the right solution.
test('Error', () => {
jest.mock('fs', () => ({
writeFile: jest.fn((path, data, callback) => callback(Error('some error')))
}));
return expect(createFile('Does not matter')).rejects.toThrow('some error');
});
But with this test there is even not a reject, so there is never thrown an error. I would appreciate if anyone could help me out there.