看起来mocking不适合我通过axios,因为它似乎使actual API调用(可见,因为我得到401状态代码时运行jest测试)我不知道为什么我不能mock axios.有人能指出我犯的错误吗?
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);
}
3条答案
按热度按时间dphi5xsq1#
您正在使用
axios
函数,而不是axios.post()
方法。所以你应该模仿axios
函数而不是axios.post()
。jest.mock()
是选择。例如
index.ts
:index.test.ts
:软件包版本:
wko9yo5t2#
尝试
在SystemUnderTest中执行
import
之前,您需要首先模拟模块。https://jestjs.io/docs/mock-functions#mocking-modules
lstz6jyr3#
对于任何想嘲笑Axios的人来说,这可能会有帮助!
https://www.npmjs.com/package/jest-mock-axios
它应该大大简化模拟过程。