简体   繁体   中英

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. 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. I prefer the latter for developer ergonomics.

Consider this UserList component that uses Axios to fetch user data:

// 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:

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);
  });
});

demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM