Search code examples
javascriptunit-testingvue.jsjestjsvue-test-utils

Vue tests - mocked axios returning undefinded


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


Solution

  • jest.mock('axios', {
        get: jest.fn(() => Promise.resolve({ status: 200, data: response })),
    });