VueJS

Vue.js Testing - Mocking HTTP Requests with axios-mock-adapter


Introduction

Testing Vue.js applications often involves making HTTP requests. To ensure reliable and predictable tests, it's essential to mock those requests. One popular tool for mocking HTTP requests is `axios-mock-adapter`, which allows you to simulate API responses for testing purposes. In this guide, we'll explore how to use `axios-mock-adapter` to mock HTTP requests in Vue.js and provide sample code to demonstrate the process.

Sample Code

Let's create a Vue.js application and mock an HTTP request using `axios-mock-adapter`:

<div id=`app`>
  <button @click=`fetchData`>Fetch Data</button>
  <div v-if=`data`>
    <h2>{{ data.title }}</h2>
    <p>{{ data.body }}</p>
  </div>
 {
        this.data = response.data;
      });
    }
  }
});
            

In this code:

  • We create a Vue component that includes a button to fetch data and a section to display the fetched data.
  • We create an instance of `axios` called `axiosInstance` and an `axios-mock-adapter` instance called `mock` to intercept and mock HTTP requests.
  • Using `mock.onGet()`, we define a mock response for the URL '/data' with a status code of 200 and sample data.
  • In the Vue instance, when the `Fetch Data` button is clicked, we use `axiosInstance` to make a GET request to '/data'. The response data is then displayed in the template when available.

Written by Surfside Media

Senior Full Stack Developer specializing in Web Technologies.