Simulating an API request using Vue and Jest/Vue test utils

Utilizing Vue for the frontend and Python/Django for the backend, I aim to create tests that verify the functionality of my API calls. However, I am encountering difficulties when attempting to mock out the Axios calls.

I suspect there might be an issue with how I have set this up. I have a function designed to be called within the component's "created" hook. This function is responsible for making a call to the backend to fetch information based on the query parameter from the URL. While it currently works as intended, I seek to understand how to mock this API request in order to enhance my testing process.

API Service: This service is used across the application to interact with 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:

The following code snippet functions correctly:

<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 represents a sample 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 })
};

Answer №1

If you're looking to simulate Axios http calls, Moxios is a handy tool that allows you to easily mock these requests. To implement this in your scenario, you can follow these steps:

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

it('Test case description...', () => {
  // Set up the axios instance exported by the api module
  moxios.install(api);

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

  // Add test logic here...
  // All axios calls to endpoints matching the given regExp will return the specified response

  moxios.uninstall();
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to instruct firebase-admin to halt during test execution?

Running process.exit() or --exit in my mocha tests doesn't feel right. I'm currently working on code that utilizes firebase-admin and while attempting to run mocha tests, wtfnode showed me: wtfnode node_modules/.bin/_mocha --compilers coffee:co ...

Custom label slots in q-file for the Quasar file picker for personalized file selection label

Can you provide guidance on how to properly display custom label slots in Quasar? I am looking to incorporate icons or images using the label slot. Below is my data(): data() { return { showLabel: true, labelText: "My custom Label& ...

Transmit JSON information from one webpage and dynamically retrieve it from another page via AJAX while both pages are active

I am attempting to transfer JSON data from page1 when the submit button is clicked and then retrieve this data dynamically from page2 using AJAX in order to display it in the console. I am unsure of the correct syntax to accomplish this task. There was a s ...

"Permission denied to access restricted URI" error encountered while attempting to utilize ng-template functionality

I am attempting to implement ng-include for recursive templates in my HTML. After testing it on jsfiddle and confirming that it works, I tried the same locally. However, I encountered the following error: Error: Access to restricted URI denied createHttpB ...

When utilizing jQuery to add a <li> element, it suddenly vanishes

? http://jsfiddle.net/AGinther/Ysq4a/ I'm encountering an issue where, upon submitting input, a list item should be created with the content from the text field. Strangely, it briefly appears on my website but not on the fiddle, and no text is appen ...

Ways to confirm that the function handed over as a prop to a Vue component operates asynchronously

How can I determine if a prop Function is asynchronous? Consider the following prop in my component: callbackFunction: { type: Function, default: null, }, Is there a way to validate this and ensure that the provided Function i ...

Utilizing the power of Vue.js and D3.js in tandem to create dynamic force simulations

Currently, I am attempting to retrieve data from a Restful API call and utilize it to create a d3.js force simulation. However, I have encountered an issue where if I use the data from the API call directly, the simulation treats it as if there is no data ...

Encountering a JavaScript error due to an erroneous character when trying to parse

I need to convert a `json` string into an object format that is extracted from a `.js` file. Here is the `JSON` string located in `document.js`: [ { "type": "TableShape", "id": "63c0f27a-716e-804c-6873-cd99b945b63f", "x": 80, ...

Organize Development and Production files in npm or webpack for improved efficiency

In React Native projects, we typically use index.android.js and index.ios.js to differentiate between the same file for Android and iOS platforms. But I wonder if it's possible to separate files based on the development and production environments as ...

What could be causing the <td> onclick event to fail in asp.net?

Having an issue with making a <td> clickable to display a div. Check out my code snippet below: <td id="tdmord" style="padding-left: 15px; color: #86A7C5; padding-right: 15px; font-family: Arial; font-size: small;" onclick="return showDiv1()"& ...

Camera Capacitor designed to eliminate popup notifications

I am utilizing Angular along with the camera plugin in Capacitor to locally save images on both desktop and tablets. I aim to utilize the CameraSource to directly access the camera or open the gallery for files without displaying a prompt. This is how my ...

What is the process of transforming async/await code into synchronous code in JavaScript?

Blocking the event loop is generally considered bad practice due to its consequences. However, even the native fs module includes some synchronous functions for specific purposes, such as CLIs using fs.readFileSync. I am interested in converting the follo ...

Is it possible to include a callback function as a property in an object in React?

I need to include a callback function in a prop of type object. I have developed a custom component for a data table where I pass columns, data, and actions as props. The actions prop consists of an array of objects with handler callback functions linked ...

What is the best way to seamlessly transition layers from one location to another as the mouse exits and re-enters the window?

I have been working on refining a parallax effect to achieve a seamless transition between two positions based on where the mouse exits and enters the window. In the JSFiddle example provided, there is a slight 'pop' that I am looking to replace ...

What are the steps to increase the size of the v-stepper-step in Vuetify?

Is there a way to adjust the size of the icon/step circle in v-stepper? ...

What is the best way to handle the keystroke event in a $.bind method?

I'm struggling with passing a specific keystroke through the bind method. $(document).bind('keyup', event, keyup_handler(event)); This is my attempt at solving it.. Here is the function it should be passed to: var keyup_handler = functio ...

What is the best way to fetch multiple values using momentjs from firebase?

After fetching data from Firebase and storing it in an array, I am attempting to retrieve the posted_at values (timestamp of when something was posted) in a time format using Vuejs. However, I am facing difficulty as it only retrieves a single value instea ...

Revamp MUI class names with React Material UI's innovative randomization and elimination

Can names be randomized or Mui-classNames removed? https://i.stack.imgur.com/J6A9V.png Similar to the image displayed? (All CSS class names would be jssXXX) Appreciate your assistance. ...

Retrieving the class name using jQuery

In my HTML code, there is a div with three classes defined as: <div class = "a b c"> .. </div> My goal is to access only the class b using the .attr() method. Is this achievable? ...

Duplication of CSRF Tokens within Vue Router on Laravel 5.3 with Vue 2 JavaScript

I am facing an issue with the session token generation. When I send the token via AJAX or AXIOS (since I am using Vue and Vue Router for API fetching), it results in a mismatch. The response I receive when posting data shows that the AJAX token does not ...