0

I want to test my Api functions which are on separate file outside vue component. Inside this methods i call api by Vue.axios, and i can't find the way to mock and test it like in this post:

How do I test axios in jest

example method:

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

example usage:

const response = await AuctionApi.cancelAuction(id);

2 Answers 2

2

Ok that was pretty obvious. I had to mock whole Vue like below:

jest.mock('vue', () => ({
  axios: {
    get: jest.fn()
  },
}));
Sign up to request clarification or add additional context in comments.

Comments

0

Just start learning Jest + @vue/test-utils. Here is a simple example for those people want to mock "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: '[email protected]' }],
      },
    }),
}));

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.