I’m seeing an issue in Jest where calling jest.clearAllMocks()
inside a beforeEach
callback seems to wipe out calls to a mocked function that are made not before but WITHIN a specific test. I can repro it as follows:
THIS PASSES:
__tests__/testy.test.js
const AWS = require("aws-sdk");
const { handler } = require("../index.js");
describe("Lambda function tests", () => {
it("sent the expected CSV data to S3", async () => {
// RUN THE LAMBDA, await completion
await handler();
// The S3 constructor should have been called during Lambda execution
expect(AWS.S3).toHaveBeenCalled();
});
});
THIS GIVES ME A FAILURE:
__tests__/testy.test.js
const AWS = require("aws-sdk");
const { handler } = require("../index.js");
describe("Lambda function tests", () => {
beforeEach(() => {
jest.clearAllMocks();
});
it("sent the expected CSV data to S3", async () => {
// RUN THE LAMBDA, await completion
await handler();
// The S3 constructor should have been called during Lambda execution
expect(AWS.S3).toHaveBeenCalled();
});
});
The failure message in the console:
expect(jest.fn()).toHaveBeenCalled()
Expected number of calls: >= 1
Received number of calls: 0
I’m using jest version 27.4.3 in Node v14.18.1. In case it matters, I’m mocking aws-sdk
like this:
__mocks__/aws-sdk.js
const AWS = jest.createMockFromModule("aws-sdk");
AWS.S3 = jest.fn().mockImplementation(() => ({
upload: jest.fn(() => ({ promise: jest.fn() })),
headObject: jest.fn(() => ({
promise: jest.fn(() => ({ ContentLength: 123 })),
})),
}));
module.exports = AWS;
What could be happening here?