[英]How can i test an API call in vuejs using jest?
im having this method in my component that makes an API call with axios, I checked the docs on how to test it but I cant seem to figure out how to do so. 我在组件中使用此方法通过axios进行API调用时,我检查了有关如何对其进行测试的文档,但似乎无法弄清楚该方法。 Any help would be appreciated.
任何帮助,将不胜感激。
loadContents() {
axios.get('/vue_api/content/' + this.slug).then(response => {
this.page_data = response.data.merchandising_page
}).catch(error => {
console.log(error)
})
},
You could use moxios
or axios-mock-adapter
to automatically mock Axios requests. 您可以使用
moxios
或axios-mock-adapter
自动模拟Axios请求。 I prefer the latter for developer ergonomics. 对于开发人员的人机工程学,我更喜欢后者。
Consider this UserList
component that uses Axios to fetch user data: 考虑使用Axios来获取用户数据的
UserList
组件:
// UserList.vue
export default {
data() {
return {
users: []
};
},
methods: {
async loadUsers() {
const { data } = await axios.get("https://api/users");
this.users = data;
}
}
};
With axios-mock-adapter
, the related test stubs the Axios GET
requests to the API URL, returning mock data instead: 使用
axios-mock-adapter
,相关的测试将Axios GET
请求存根到API URL,而是返回模拟数据:
import axios from "axios";
const MockAdapter = require("axios-mock-adapter");
const mock = new MockAdapter(axios);
import { shallowMount } from "@vue/test-utils";
import UserList from "@/components/UserList";
describe("UserList", () => {
afterAll(() => mock.restore());
beforeEach(() => mock.reset());
it("loads users", async () => {
mock
.onGet("https://api/users")
.reply(200, [{ name: "foo" }, { name: "bar" }, { name: "baz" }]);
const wrapper = shallowMount(UserList);
await wrapper.vm.loadUsers();
const listItems = wrapper.findAll("li");
expect(listItems).toHaveLength(3);
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.