手动模拟
您可以在utilities.js 的同一级别创建__mocks__ 目录,然后在此目录中创建一个名为utilities.js 的文件。
utilities.js
const speak = () => "Function speak";
const add = (x, y) => x + y;
const sub = (x, y) => x - y;
module.exports = { speak, add, sub };
现在,保持一切不变,然后模拟 speak 函数。
__mocks__/utilities.js
const speak = jest.fn(() => "Mocked function speak");
const add = (x, y) => x + y;
const sub = (x, y) => x - y;
module.exports = { speak, add, sub };
现在你可以模拟utilities.js
utilities.test.js
const { speak, add, sub } = require("./utilities");
jest.mock("./utilities");
test("speak should be mocked", () => {
expect(speak()).toBe("Mocked function speak");
});
模拟节点模块
在node_modules 的同级创建一个名为__mocks__ 的目录,并在该目录中添加一个文件'axios.js'。
__mocks__/axios.js
const axios = {
get: () => Promise.resolve({ data: { name: "Mocked name" } }),
};
module.exports = axios;
fetch.js
const axios = require("axios");
const fetch = async () => {
const { data } = await axios.get(
"https://jsonplaceholder.typicode.com/users/1"
);
return data.name;
};
module.exports = fetch;
使用节点模块,您无需显式调用jest.mock("axios")。
fetch.test.js
const fetch = require("./fetch");
test("axios should be mocked", async () => {
expect(await fetch()).toBe("Mocked name");
});