Building up on @aayla-secura's response, if you want to test both send
call results (the one that resolves and the one that rejects), what you could do is declare the send mock as a separate const
The idea of using an arrow function comes from this other contribution: https://stackoverflow.com/a/68073694/12194386
const mockSend = jest.fn();
jest.mock("@aws-sdk/client-s3", () => ({
PutObjectCommand: jest.fn(),
S3Client: jest.fn(() => ({
send: () => mockSend(),
})),
}));
Another solution found in the Jest documentation (see https://jestjs.io/docs/es6-class-mocks) could be to use mockImplementation
:
const mockSend = jest.fn();
jest.mock("@aws-sdk/client-s3", () => ({
PutObjectCommand: jest.fn(),
S3Client: jest.fn().mockImplementation(() => ({
send: mockSend,
}));
}));
That way, you have the possibility to mock different behaviors
describe("upload product", () => {
it("should send status 502 if saving image fails", async () => {
mockSend.mockRejectedValueOnce(new Error('Some error'));
...
await uploadProductHandler(mockReq, mockRes);
...
expect(mockRes.sendStatus).toHaveBeenCalledWith(502);
});
it("should send status 201 when everything works correctly", async () => {
mockSend.mockResolvedValueOnce(null);
...
await uploadProductHandler(mockReq, mockRes);
...
expect(mockRes.sendStatus).toHaveBeenCalledWith(201);
});
});