79258573

Date: 2024-12-06 15:44:47
Score: 1
Natty:
Report link

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);
  });
});
Reasons:
  • Blacklisted phrase (1): stackoverflow
  • Long answer (-1):
  • Has code block (-0.5):
  • User mentioned (1): @aayla-secura's
  • Low reputation (0.5):
Posted by: JrmDel