It seems mocking is not working for me via axios as it seems to make acrtual API calls ( visible because I am getting 401 status code when running jest test ) I am not sure why am I not able to mock axios.Can anyone point out the mistake I am making?
index.test.ts
describe("compositeScore()", () => {
it("Mock Fetch API for Composite Score Response", async () => {
const mock = jest.spyOn(axios, "post");
mock.mockReturnValueOnce(mockResponse);
const response = await dateFilter(platform);
expect(mock).toHaveBeenCalledTimes(1);
expect(response).toEqual(mockFetchCompositeScoreResponse);
});
});
index.ts
export const dateFilters = async (platform) => {
const dates = await fetchWrapper(
platform.toLowerCase().concat("DateFilters"),
platform,
{}
);
return dates;
};
export async function fetchWrapper(
queryName: string,
platform: string,
queryParams?: {}
) {
const headers = {
Accept: "application/json",
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
};
const config: AxiosRequestConfig = {
method: "post",
url,
headers,
data: {
db: dbName,
csl: queryParams
? substituteQueryParameters(queries[queryName], queryParams)
: queries[queryName],
},
};
return axios(config);
}
Try
import axios from 'axios';
jest.mock('axios');
You'll need to mock the module first before you import
in the System Under Test.
You are using axios
function, not axios.post()
method. So you should mock axios
function rather than axios.post()
. jest.mock()
is the choice.
Eg
index.ts
:
import axios, { AxiosRequestConfig } from 'axios';
export const dateFilters = async (platform) => {
const dates = await fetchWrapper(platform.toLowerCase().concat('DateFilters'), platform, {});
return dates;
};
export async function fetchWrapper(queryName: string, platform: string, queryParams?: {}) {
const token = '123';
const url = 'http://localhost:3000/api';
const dbName = 'test';
const headers = {
Accept: 'application/json',
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json',
};
const config: AxiosRequestConfig = {
method: 'post',
url,
headers,
data: {
db: dbName,
},
};
return axios(config);
}
index.test.ts
:
import axios, { AxiosResponse } from 'axios';
import { dateFilters } from '.';
jest.mock('axios');
const mAxios = axios as jest.MockedFunction<typeof axios>;
describe('71351319', () => {
it('Mock Fetch API for Composite Score Response', async () => {
const mockResponse = { data: {}, status: 200, statusText: 'ok' } as AxiosResponse;
mAxios.mockResolvedValue(mockResponse);
const response = await dateFilters('DateFilters');
expect(mAxios).toHaveBeenCalledTimes(1);
expect(response).toEqual({ data: {}, status: 200, statusText: 'ok' });
});
});
package versions:
"axios": "^0.21.1",
"jest": "^26.6.3",
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.