我在我的Vue.js应用程序中使用VueAxios包装程序进行HTTP请求。
这是我的API服务的简化版:
//api.service.js
import Vue from "vue";
import axios from "axios";
import VueAxios from "vue-axios";
const ApiService = {
init() {
Vue.use(VueAxios, axios);
},
get(resource, id = "") {
return Vue.axios.get(`${resource}/${id}`);
},
以及我的(简化且失败的)API测试:
// api.spec.js
import Vue from "vue";
import axios from "axios";
import VueAxios from "vue-axios";
import {createLocalVue} from "@vue/test-utils";
jest.mock("axios");
jest.mock("vue-axios"); // Not sure if I need one or both or neither.
describe("the running store actions test", () => {
const localVue = createLocalVue();
localVue.use(VueAxios, axios);
test("that a resource is fetched via the API", async () => {
Vue.axios.get.mockImplementationOnce(() =>
Promise.resolve({
data: {}
})
);
...
// Some test calling the get() method in api.service.js above.
});
问题是运行测试时出现以下错误:
TypeError: Cannot read property 'get' of undefined
42 |
> 43 | Vue.axios.get.mockImplementationOnce(() =>
| ^
44 | Promise.resolve({
45 | data: {}
46 | })
at Object.get (tests/unit/store/api.spec.js:43:19)
我通过将api.spec.js文件更改为不使用VueAxios,然后正常地模拟了Axios,例如,
get(resource, id = "") {
return axios.get(`${resource}/${id}`).catch(error => {
throw new Error(`ApiService ${error}`);
});
},
然后,测试将运行并顺利通过。
但是,我想使用VueAxios通过测试。任何想法将不胜感激。