如何嘲笑VueAxios

时间:2020-07-29 09:17:44

标签: vue.js testing jestjs axios

我想测试vpi组件之外单独文件中的Api函数。在这种方法中,我通过Vue.axios调用api,但找不到像本文中那样模拟和测试它的方法:

How do I test axios in jest

示例方法:

cancelAuction: function (auction_id) {
    if (validateApiInt(auction_id)) {
      return Vue.axios.delete(`/auctions/${auction_id}`);
    }
    return {};
  },

用法示例:

const response = await AuctionApi.cancelAuction(id);

2 个答案:

答案 0 :(得分:2)

好吧,这很明显。我不得不像下面这样模拟整个Vue:

jest.mock('vue', () => ({
  axios: {
    get: jest.fn()
  },
}));

答案 1 :(得分:0)

刚开始学习 Jest + @vue/test-utils。这是一个简单的例子,供那些想要模拟“vue-axios”的人使用。

// @/components/Helloword.vue

<template>
  <div>
    <h1>Email: <span>{{ email }}</span></h1>
    <button @click="fetchData">Get Random Email</button>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  data() {
    return {
      email: '',
    };
  },
  methods: {
    async fetchData() {
      const res = (await this.axios.get('https://randomuser.me/api/')).data
        .results[0].email;
      this.email = res;
    },
  },
};
</script>

--

    // test/unit/example.spec.js

import { mount } from '@vue/test-utils';
import HelloWorld from '@/components/HelloWorld.vue';
import axios from 'axios';

jest.mock('axios', () => ({
  get: () =>
    Promise.resolve({
      data: {
        results: [{ email: 'mockAxios@email.com' }],
      },
    }),
}));

describe('HelloWorld.vue', () => {
  it('click and fetch data...', async (done) => {
    const wrapper = mount(HelloWorld, {
      mocks: {
        axios,
      },
    });

    await wrapper.find('button').trigger('click');

    wrapper.vm.$nextTick(() => {
      expect(wrapper.find('h1').text()).toContain('@');
      done();
    });
  });
});