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: "example@example.com",
        username: "test",
        isTenant: false,
        getRole: "RegularUser"
      },
      {
        id: 2,
        email: "example@example.com",
        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

skyboyer
  • 22,209
  • 7
  • 57
  • 64

1 Answers1

3
jest.mock('axios', {
    get: jest.fn(() => Promise.resolve({ status: 200, data: response })),
});
liborkozak
  • 474
  • 4
  • 4
  • 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. – borchvm Mar 17 '20 at 07:31