0

I'm having trouble writing unit tests with axios. When I mock axios, it returns undefinded. I'm using vue-test-utils and jest (see code below). I've checked the documentation, but can't figure it out.

import { shallowMount } from '@vue/test-utils';
import flushPromises from 'flush-promises';
import Vue from 'vue';
import Vuetify from 'vuetify';
import axios from 'axios';
import FrontendUser from '@/views/Users/FrontendUser';
import store from '@/store';
import "@/config/axios";

jest.mock('axios');

Vue.use(Vuetify);

describe("FrontendUser.vue", () => {
  test("Data are download successfully", async () => {
    const wrapper = shallowMount(FrontendUser, {
      store,
      mocks: {
        $t: () => { },
      }
    });
    const vm = wrapper.vm;
    const response = [
      {
        id: 1,
        email: "[email protected]",
        username: "test",
        isTenant: false,
        getRole: "RegularUser"
      },
      {
        id: 2,
        email: "[email protected]",
        username: "test",
        isTenant: true,
        getRole: "RegularUser"
      }
    ]
    axios.get.mockImplementation(() => Promise.resolve({ status: 200, data: response }))
    await flushPromises();
    expect(vm.frontendUsers.length).toBeGreaterThan(0);
  })

});

Here's a screenshot of the error: enter image description here

3
  • 1
    Welcome to S/O. Usually it's preferred to copy paste the error as text rather than show a screenshot. For example, images aren't even working right now! Plus an answerer might want to copy the error. Commented Mar 16, 2020 at 13:28
  • Thank you for answer, but I slove this problem :D Commented Mar 16, 2020 at 13:34
  • Glad you solved it Commented Mar 16, 2020 at 13:34

1 Answer 1

3
jest.mock('axios', {
    get: jest.fn(() => Promise.resolve({ status: 200, data: response })),
});
Sign up to request clarification or add additional context in comments.

1 Comment

While this code may provide a solution to the question, it's better to add context as to why/how it works. This can help future users learn, and apply that knowledge to their own code. You are also likely to have positive feedback from users in the form of upvotes, when the code is explained.

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.