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

Encountering an undefined error for 'orderBy' while running tests on a Vue component that utilizes lodash in combination with Jest

Using Vue.js, I have successfully imported lodash into my main.js file like so: import lodash from 'lodash' Vue.use(VueLodash, lodash) Now, within my single file components, I am able to utilize the lodash orderBy function with ease: this._.or ...

CSS for when the mouse hovers over an element

Two php files and a js file are involved in this scenario. The issue at hand is that when the div is clicked, it navigates to a new page with an appended # to the URL, causing it to scroll to the specified comment ID. However, instead of scrolling to the c ...

Issue with React's handleChange function in two separate components

I need assistance with calling the event handleChange from a second Component This is my principal component: const [mainState, setMainState] = useState({ stepValue: 1, saleDateVal: new Date(), customerVal: '' }); function moveNextStep() { ...

show data pulled from localStorage

I'm struggling to figure out how to use localStorage for the first time, specifically in storing an array of objects and displaying that information even after page refresh. Currently, I can see that it is being stored but not displayed. const book ...

What methods can be used to accomplish this effect using CSS and/or Javascript?

Is there a way to achieve the desired effect using just a single line of text and CSS, instead of multiple heading tags and a CSS class like shown in the image below? Current Code : <h2 class="heading">Hi guys, How can i achieve this effect using j ...

Could you explain the distinction between these two arrow functions?

I'm puzzled about why the second arrow function is effective while the first one isn't. //the first one doesn't function properly this.setState = () => { text: e.target.value, }; //in contrast, this one ...

Executing a scroll down action with Selenium in combination with Node.js and the Chai/Mocha testing framework

Browser: Chrome Looking for ways to scroll up or down using Selenium with Node.js (JavaScript). ...

Exploring the methods for interpreting a JSON object within a Vue.js framework

Here is the json object I am working with: const faqs = [{'question1':'answer1'},{'question2':'answer2'}] In my Vue.js code, I am attempting to iterate through this data using a for loop within a div like so: <di ...

How can I manage file input within a Vue.js application?

After attempting to open a file input with a button, I encountered an issue. When clicking the button, the client reported: “this.$refs.image.click”. Below is my code snippet: <v-btn height="50" ...

"Utilizing Material-UI in React to create a textfield input with number validation

I am currently working on an input field that should only accept values within a specified range of min and max. However, I have encountered an issue where manually entering a number bypasses this control mechanism. Is there a way to prevent this from happ ...

Tips for transferring slot/data to an inertia layout component

How can a slot or prop be passed to a layout component in inertia? For instance, consider the ForgotPassword component: <template> <slot name="title">Forgot Password</slot> Forgot password content here... </template ...

JavaScript's XMLHttpRequest

My attempt to bypass the WebGoat prompt involved using a combination of javascript code with XMLHttpRequest to send multiple requests, one using GET and the other using POST. The code snippet is as follows: <script> var req1 = new XMLHttpRequest() ...

Remove option from MUI Autocomplete after it has been selected

I am currently utilizing a Material-UI Autocomplete component. To avoid users selecting the same element twice, resulting in duplicate ID numbers, I want to remove the element from the dropdown entirely. For instance, if "Shawshank Redemption" is selected ...

What is the best way to manage zoom settings following a completed search query?

Whenever I try to search for an address using this map, it zooms in way too much making the map unusable. Despite my efforts to adjust the map bounds, I have not been successful. It seems like I am on the right track but for some reason, it just isn't ...

Identify modifications in the input and at the same time update another input

I currently have two input text boxes. My goal is to synchronize the content of the second input box whenever the first input box is changed. I attempted to achieve this using this code snippet. However, I encountered an issue where the synchronization on ...

Using jQuery to show/hide linked CSS3 animations upon Mouseenter/Mouseleave events

Exploring the capabilities of animate.css and jQuery within a bootstrap environment has been quite interesting for me. However, I've encountered a major issue! I am attempting to trigger animations on mouseenter / mouseleave, which led me to create a ...

What is the best way to retrieve information from an API and save it in an array within a MongoDB schema?

My current challenge involves querying an API in node.js, storing the obtained data in an array, and then pushing that array to a MongoDB schema. However, I am encountering difficulties as I am receiving an 'unhandledpromiserejection' warning err ...

How to Use AJAX, jQuery, and JSON to Send an Array to PHP

I'm attempting to send an associative array through AJAX $.post to a PHP script. Below is the code I am using: var request = { action: "add", requestor: req_id, ... } var reqDetails = $("#request_details").val(); ...

The page does not seem to be reloading properly due to a redirect issue

I am currently updating some data and then attempting to reload the current page. After discovering the status code that allows me to switch the redirect method from put to get (303), I noticed that it is functioning correctly. However, despite seeing "fi ...

Instructions on transferring an image to a server. The image is located on the client side within an <img> tag

Looking for an effective way to upload an image when the type is “file”? The goal here is to send an image from an image tag to the server without converting it into base64 due to size constraints. <form id="form-url"> <image src ...