Mocking an API call with Vue and Jest/Vue test utils

Asked By: Anonymous

I’m using Vue for the frontend and Python/Django for the backend. I would like to write tests to ensure that my API calls to my backend are working as expected but I’m having trouble mocking out the Axios calls.

I’m probably set this up wrong but you can see that I have one function that is meant to be called inside of the components “created” hook. Thus when the component is created this function makes a call to my backend to retrieve information based on the query parameter that comes with the URL. This all works but I want to learn how to mock this API request to write better tests.

API Service This is used throughout the app to call the backend.

file path: src/api/api.js

import axios from "axios";
import { djangoServiceUser } from "../../config.js";

export default axios.create({
  baseURL: "/api",
  timeout: 5000,
  headers: {
    "Content-Type": "application/json",
    Authorization: `Token ${djangoServiceUser}`
  }
});

Single File Component

This does work:

<script>
import api from "@/api/api";

export default {
  data() {
    return {
      loading: false,
      userBusinessOptions: null
    };
  },
  methods: {
    fetchBusinesses(fwt_user_id) {
      this.loading = true;

      api.get(`companies/${fwt_user_id}`).then(
        response => {
          this.loading = false;
          let businessNames = [];
          for (let i in response.data) {
            businessNames.push(response.data[i].name);
          }
          this.userBusinessOptions = businessNames;
        },
        error => {
          this.loading = false;
        }
      );
    }
  },
  created() {
    this.fetchBusinesses(this.$route.query.fwt_user_id);
  }
};
</script>

beginApplicationVueTest.test.js
file path: src/views/tests/beginApplicationVueTest.test.js

import { shallowMount } from "@vue/test-utils";
import BeginApplication from "@/views/BeginApplication.vue";
import Vuetify from "vuetify";
import Vue from "vue";
import api from "@/api/__mocks__/api";

Vue.use(Vuetify);

it("fetches businessses", () => {
  const $route = {
    query: { fwt_user_id: 35 }
  };
  const wrapper = shallowMount(BeginApplication, {
    mocks: {
      $route
    }
  });
  expect(wrapper.vm.$route.query.fwt_user_id).toBe(35);

  wrapper.vm.fetchBusinesses(wrapper.vm.$route.query.fwt_user_id);
  wrapper.vm.$nextTick(() => {
    expect(wrapper.vm.userBusinessOptions).toBe("test");
    done();
  });
});

Attempted mock API?
file-path: src/api/mocks/api.js

assume business_list.json is an example JSON response from the API.

[
  {
    "id": 90,
    "user": 67
  },
  {
    "id": 89,
    "user": 67
  }
]
import businessList from "./data/business_list.json";

export default {
  get: () => Promise.resolve({ data: businessList })
};

Solution

Answered By: Anonymous

You can use Moxios to mock Axios http calls easily. For your use case, you can do something like this:

import moxios from 'moxios'; // you have to npm install moxios
import api from './path/to/api.js';
import businessList from './path/to/business_list.json';

it('...', () => {
  // Install the axios instance the api module is exporting
  moxios.install(api);

  moxios.stubRequest(new RegExp('.*?/api/comapines.*'), {
    status: 200,
    response: { data: businessList }
  });


  // Test body...
  // Any axios call to an endpiont that matches the regExp would always return the response specified

  moxios.uninstall();
})
techinplanet staff

techinplanet staff


Windows 10 Kaufen Windows 10 Pro Office 2019 Kaufen Office 365 Lizenz Windows 10 Home Lizenz Office 2019 Home Business Kaufen windows office 365 satın al follower kaufen instagram follower kaufen porno