docs
  1. Testing Your Add-on

Testing your Add-on

In this guide you will set up and use Vitest in a Vue Single Page Application (SPA) to test components and services. Specifically, you will learn how to mock an external API called MyCustomBackendAPI, which retrieves permissions for the current user. We will be using the vi helper from Vitest to handle the mocking.

Prerequisites

  • Node.js and npm installed
  • A Vue 3 project set up with Vite
  • Vitest installed and configured in your project

Installing Vitest

If you haven’t already installed Vitest, you can do so by running:

Configuring Vitest in a Vue project

Ensure that your vite.config.js file includes the necessary configuration for Vitest:

Setting up a backend service

Assume you have a service that interacts with an external API to fetch permissions for the current user. Here's a simple example of what MyCustomBackendAPI.js might look like:

Writing a Component that Uses MyCustomBackendAPI

Here's an example of a Vue component that uses the MyCustomBackendAPI service:

Setting up tests with Vitest

Installing necessary test utilities

To write and run tests, install the following utility packages:

Writing a test with Vitest and mocking MyCustomBackendAPI

Let's write a test for our Vue component, ensuring that we mock the MyCustomBackendAPI to avoid actual HTTP requests during the test:

Explanation of the test code

  • vi.spyOn: This Vitest helper is used to mock MyCustomBackendAPI.getUserPermissions so that it returns a controlled response without making an actual HTTP request.
  • mockResolvedValue: Simulates a successful API response.
  • mockRejectedValue: Simulates an API failure scenario.
  • mount: Provided by @vue/test-utils, this function mounts the Vue component in a test environment.
  • await wrapper.vm.$nextTick(): Ensures that the component has finished processing any asynchronous actions before assertions are made.
  • Assertions: Checks if the permissions are correctly rendered based on the mocked API response.

Running the Tests

To run your tests using Vitest, simply execute:

You can also run tests in watch mode with: