由于某种原因,无论我在玩笑中做什么配置,我都无法模拟我的httpService。当测试运行时,它仍然尝试连接到真正的后端。我知道这一点,因为我从终端
得到了这样的错误● call to add task endpoint
connect ECONNREFUSED 127.0.0.1:5000
这是我的文件:
taskService.test.ts
import task from "./taskService";
beforeEach(() => jest.resetModules());
test("call to add task endpoint", async () => {
jest.doMock("./httpService", () => ({
__esModule: true,
default: {
post: jest.fn(() => {}),
},
}));
const httpService = require("./httpService");
await task.add("Go To Market", "2021-02-28");
expect(httpService.post).toHaveBeenCalledWith("/tasks", {
task: "Go To Market",
date: "2021-02-28",
});
});
taskService.ts
import httpService from "./httpService";
const add = async (task: string, date: string) => {
await httpService.post("/tasks", {
date,
task,
});
};
export default {
add,
};
httpService.ts
import axios from "axios";
export default {
get: axios.get,
post: axios.post,
put: axios.put,
delete: axios.delete,
};
文件夹结构如下:
services
- httpService.ts
- taskService.test.ts
- taskService.ts
要使模拟正常工作,它应该与require/import
语句(在本例中是taskService
导入)处于相同的作用域。这意味着我们不能使用jest.doMock
,因为它不会像jest.mock
那样被提升到import
语句之上。检查这个答案,了解jest.mock
和jest.doMock
之间的区别。
import task from './taskService'
import httpService from './httpService'
jest.mock('./httpService', () => ({
post: jest.fn(),
}))
beforeEach(() => jest.resetModules())
test('call to add task endpoint', async () => {
await task.add('Go To Market', '2021-02-28')
expect(httpService.post).toHaveBeenCalledWith('/tasks', {
task: 'Go To Market',
date: '2021-02-28',
})
})