In my testing process, I am attempting to simulate the behavior of an npm package. Specifically, I want to create a scenario where the package returns a Promise that resolves to true in one test and rejects with an error in another.
To achieve this, I have set up a mock implementation of the npm package at the beginning of my test file, just before the initial test description. The code for mocking the npm package looks like this:
const mockNewFile = (): File => new File(['this is new file content'], 'new-file');
jest.mock('blueimp-load-image', () => () => {
const newFile = mockNewFile();
return new Promise(resolve => {
const data = {
image: {
toBlob: (func: (file: File) => File) => {
func(newFile);
}
}
};
resolve(data);
});
});
By setting up this mock, I can successfully run tests for functions that rely on the blueimp-load-image
npm package.
However, I also wanted to include a test case for when the blueimp-load-image
function fails to fulfill its promise and returns an error. To do this, I created a new test block within the main test description and attempted to mock the npm package again to return an error:
describe('if loadImage returns an error', () => {
beforeEach(() => {
jest.mock('blueimp-load-image', () => () => {
return new Promise((resolve, reject) = reject(new Error('something went wrong')));
});
});
test('return the file back unmodified', async () => {
const expected = {/* file content */};
const result = await theFunctionUsingLoadImage(file);
expect(result).toStrictEqual(expected);
});
});
The above test does not work as expected, as no error is thrown. This leads me to believe that the mock setup in the beforeEach
block is not functioning properly. I have also tried using jest.spyOn instead of Jest.mock, but that approach was unsuccessful.
I am unsure of what I am missing or overlooking in this testing scenario. Can anyone provide guidance?