【发布时间】:2021-03-14 14:15:44
【问题描述】:
我尝试测试我的 API 调用。 我正在使用:
- VueJS
- 开玩笑
- Axios
我在运行此测试时收到错误:“_axios.default.post.mockImplementationOnce 不是函数”:
import axios from 'axios'
let url = ''
let body = {}
jest.mock("axios", () => ({
//__esModule: true,
post: (_url, _body) => {
return new Promise((resolve) => {
url = _url
body = _body
resolve(true)
})
}
}))
//axios.mockResolvedValue();
describe('getGameList', () => {
test('Success: should return the game list of the user and update gameList in the store', async () => {
const response = {
data: [
{ id:1, name:"game_name1" },
{ id:2, name:"game_name2" }
]
};
//axios.post.mockResolvedValue(response);
//OR
axios.post.mockImplementationOnce(() => Promise.resolve(response));
expect(url).toBe("api/game_list_of_user")
expect(body).toStrictEqual({"user_id": 1})
});
});
有什么线索吗?
编辑1:在tmhao2005的帮助下:
jest.mock("axios", () => ({
post: jest.fn((_url, _body) => {
url = _url
body = _body
return Promise.resolve();
}),
create: jest.fn(function () {
return this;
})
}))
describe('getGameList', () => {
test('Success: should return the game list of the user and update gameList in the store', async () => {
const url = "api/game_list_of_user";
const body = {
"user_id": 1
};
const response = {
data: [
{ id:1, name:"game_name1" },
{ id:2, name:"game_name2" }
]
};
axios.post.mockResolvedValue(response); //OR axios.post.mockImplementationOnce(() => Promise.resolve(response));
expect(url).toBe("api/game_list_of_user")
expect(body).toStrictEqual({"user_id": 1})
expect(axios.post).toHaveBeenCalledTimes(1);
});
});
看起来我的模拟 axios 没有被调用。 toHaveBeenCalledTimes 方法是正确的调用方法吗?
编辑 2: 我调用了我的操作并尝试模拟我的上下文。
let url = ''
let body = {}
jest.mock("axios", () => ({
post: jest.fn((_url, _body) => {
return new Promise((resolve) => {
url = _url
body = _body
resolve(true)
})
})
}))
//https://medium.com/techfides/a-beginner-friendly-guide-to-unit-testing-the-vue-js-application-28fc049d0c78
//https://www.robinwieruch.de/axios-jest
//https://lmiller1990.github.io/vue-testing-handbook/vuex-actions.html#testing-actions
describe('getGameList', () => {
test('Success: should return the game list of the user and update gameList in the store', async () => {
//const commit = jest.fn()
const MockContext = jest.fn(() => {
let context= {
state: {
user: {
id:1
}
}
}
return context
});
const response = {
data: [
{ id:1, name:"game_name1" },
{ id:2, name:"game_name2" }
]
};
axios.post.mockResolvedValue(response); //OR axios.post.mockImplementationOnce(() => Promise.resolve(response));
await actions.getGameList(axios.post, MockContext)
expect(url).toBe("api/game_list_of_user")
expect(body).toStrictEqual({"user_id": 1})
expect(axios.post).toHaveBeenCalledTimes(1)
//expect(commit).toHaveBeenCalledWith(mutations.UpdateGameList, true)
});
test('Error: an error occurred', () => {
const errorMessage = 'Error';
axios.post.mockImplementationOnce(() =>
Promise.reject(new Error(errorMessage))
);
});
});
【问题讨论】: