[英]Jest Mocked Function not calling mocked axios instance function (returns undefined)
我首先遵循这个 StackOverflow 问题中的答案
但是我添加了一个我使用的助手 function,它使用与用户关联的身份验证令牌创建一个新的 Axios 实例。
看起来有点像这样:
import axios from "axios";
const mockAxios: jest.Mocked<typeof axios> = jest.createMockFromModule("axios");
// this is the key to fix the axios.create() undefined error!
mockAxios.create = jest.fn(() => {
return mockAxios;
});
export const createAuthenticatedInstance = () => {
return mockAxios.create();
};
export default mockAxios;
为什么 mockAxios.create() 返回未定义?
虽然定义了 object 'mockAxios'(和创建函数)。 当我实际调用 create 时,尽管声明了 function,它仍返回 undefined。
我知道我可以通过返回 mockAxios 来回避这个问题,但我想了解为什么它首先不起作用。 我期望的是返回一个新实例,它与 mockAxios 相同,但它只是返回未定义的。
如果你正在创建一个自动模拟(在__mocks__
内),它意味着是模块的模拟,并且任何辅助函数都不应该在模块内,但可能在你的代码的其他地方
例子:
src/axios.utils.ts
(导出 axios 和函数的实用模块)
import axios from "axios"; export const createAuthenticatedInstance = (...args: Parameters<typeof axios.create> ) => { return axios.create(...args); }; export default axios;
src/__mocks__/axios.ts
(axios 模拟)
const axios: jest.Mocked<typeof import("axios").default> = jest.createMockFromModule( "axios" ); axios.create.mockReturnThis(); export default axios;
src/api.ts
(使用axios.util
的 api 实现)
import api from "./api";
import axios, { AxiosResponse } from "axios";
jest.mock("axios");
const { get } = axios as jest.Mocked<typeof import("axios").default>;
describe("api", () => {
it("should have created an axios instance", () => {
expect(axios.create).toHaveBeenCalledWith({
baseURL: "http://example.com:80/main",
});
});
})
src/api.spec.ts
(测试)
import api from "./api"; import axios, { AxiosResponse } from "axios"; jest.mock("axios"); const { get } = axios as jest.Mocked<typeof import("axios").default>; describe("api", () => { it("should have created an axios instance", () => { expect(axios.create).toHaveBeenCalledWith({ baseURL: "http://example.com:80/main", }); }); })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.