I am trying to do a simple mock for my get All method.I'm getting this error:
Expected number of calls: 1 Received number of calls: 0
following is my mock configurations.
jest.mock("axios", () => {
return {
create: jest.fn(() => ({
get: jest.fn(() => Promise.resolve({ data: [{ name: "test_role" }] })),
post: jest.fn(() => Promise.resolve({ data: { name: "test_role" } })),
put: jest.fn(() => Promise.resolve({ data: { name: "updated_role" } })),
delete: jest.fn(() => Promise.resolve({ data: "" })),
interceptors: {
request: { use: jest.fn(), eject: jest.fn() },
response: { use: jest.fn(), eject: jest.fn() },
},
})),
};
});
here is my test:
it("get all roles", async () => {
//Arrange
const allRoles = [{ name: "test_role" }];
//Act
const result = await role.getAll();
//Assert
expect(JSON.stringify(result.data)).toBe(JSON.stringify(allRoles));
expect(jest.fn()).toHaveBeenCalledTimes(1);
});
CodePudding user response:
jest.fn()
creates a new mock function and has no reference to other functions that it was used to create. Hence, you will need to explicitly define which mock function you expect to have been called. E.g. if you wanted post
to be called - you will need to define this as follows:
expect(axios.create.post).toHaveBeenCalledTimes(1);
You can reuse this syntax to expect other method calls.