'Mocking axios using interceptors (issue)
When running the following test to check if the login endpoint is being called with given arguments...
jest.mock("axios", () => {
return {
create: () => {
return {
interceptors: {
request: { eject: jest.fn(), use: jest.fn() },
response: { eject: jest.fn(), use: jest.fn() },
},
};
},
};
});
const mockedAxios = axios as jest.Mocked<typeof axios>;
it("should call login endpoint with given arguments", async () => {
render(<MainContextProvider />);
const mockedResponse = {
succeeded: true,
token: "eyJhbGc",
firstName: "Test",
lastName: "Test",
email: "[email protected]",
roles: ["Client"],
};
const { login } = authApi();
mockedAxios.post.mockResolvedValue(mockedResponse);
await login("[email protected]", "1234");
expect(axios.post).toHaveBeenCalledWith(
`${process.env.REACT_APP_URL_IDENTITY}/login`
);
expect(axios.post).toHaveBeenCalled();
});
I have the following error regarding mockResolvedValue property:
TypeError: Cannot read properties of undefined (reading 'mockResolvedValue')
231 | const { login } = authApi(); 232 | > 233 | mockedAxios.post.mockResolvedValue(mockedResponse); | ^ 234 | await login("[email protected]", "1234");
authApi.js
const authApi = function () {
const context = this;
const identityService = axios.create({
baseURL: process.env.REACT_APP_URL_IDENTITY,
});
identityService.interceptors.request.use(
(config) => {
config.headers.authorization = context.state.securityToken || null;
return config;
},
(error) => Promise.reject(error)
);
return {
login: async (email, pinCode) => {
const request = { username: email, password: pinCode };
const { data } = await identityService.post("/login", request);
return data;
},
};
};
export default authApi;
Any ideas on how to fix this issue and make the test pass?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
