Mocking API Calls in Vue Tests

Tutorial 3 of 5

Mocking API Calls in Vue Tests

Introduction

In this tutorial, we'll aim to understand how to mock API calls when testing Vue applications. Mocking API calls allows us to simulate the behavior of real APIs, making our tests more reliable and predictable.

By the end of this tutorial, you will learn:
- What is API Mocking and why it is important
- How to mock API calls in Vue applications
- How to write and run tests that include mocked API calls

Prerequisites:
- Basic knowledge of Vue.js
- Familiarity with JavaScript
- Basic understanding of API and HTTP requests

Step-by-Step Guide

What is API Mocking?

API Mocking involves simulating the behavior of a real API and returning predefined data. It is a powerful feature for writing tests as it enables you to isolate your code from any external dependencies, making your tests faster and more predictable.

Mocking API Calls in Vue

In Vue, we can use libraries like axios-mock-adapter to mock HTTP requests. This is especially useful when we want to test components that rely on API calls.

Writing and Running Tests

In the Vue ecosystem, the Jest testing framework is commonly used. Jest provides a range of features to write effective unit tests, including a built-in mocking library.

Code Examples

Let's consider a simple Vue component that fetches user data from an API using Axios:

<template>
  <div>
    {{ user.name }}
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      user: null
    }
  },
  async created() {
    const response = await axios.get('/api/user');
    this.user = response.data;
  }
}
</script>

To test this component, we can use the axios-mock-adapter library to mock the API call:

import { shallowMount } from '@vue/test-utils';
import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';
import User from '@/components/User.vue';

describe('User.vue', () => {
  let mock;

  beforeEach(() => {
    mock = new MockAdapter(axios);
  });

  afterEach(() => {
    mock.restore();
  });

  it('fetches user data when component is created', async () => {
    const userData = { name: 'John Doe' };
    mock.onGet('/api/user').reply(200, userData);

    const wrapper = shallowMount(User);

    await wrapper.vm.$nextTick();

    expect(wrapper.text()).toBe('John Doe');
  });
});

In this test, we first create a new MockAdapter instance before each test and restore it after each test. In the test itself, we tell the mock adapter to respond with a 200 status and some predefined user data when a GET request is made to '/api/user'. We then mount the component and wait for the Vue updates to finish with $nextTick(). At the end, we verify that the component renders the correct user name.

Summary

In this tutorial, we learned about API Mocking and its importance. We explored how to mock API calls in Vue applications using axios-mock-adapter and how to write and run tests that include mocked API calls.

As next steps, you can explore further the libraries mentioned here and try mocking more complex API interactions.

Practice Exercises

  1. Write a test for a Vue component that makes a POST request to '/api/user' and updates its data accordingly.
  2. Write a test that handles failed API calls. Mock the API to return a 500 status and check if your component behaves correctly.

Remember, practice is the key to mastering any concept. Happy coding!