This article explains how to write unit tests for a CLI application using Vitest and @testing-library/react
.
Note: While this article's flow uses Vitest specifically, the CLI is framework-agnostic and supports any testing library.
This article covers:
Before getting started, make sure that:
Run the following command to install the required packages:
Note: Since the Wix CLI uses React 16, we currently only support version 12 of @testing-library/react
.
Create or update your vitest.config.js
file with the following configuration:
Create a test setup file at tests/setup.ts
. This file is used for general test configuration with Vitest:
Add the following script to your package.json
file to trigger unit tests:
Depending on your app's functionality, testing your app's react components may involve mocking Wix Javascript SDK APIs, backend interactions, or both.
To test a react component like a dashboard page, check that aspects of the component would be rendered correctly.
For example, given the following dashboard page:
You can test whether the “Dashboard Page” text would be present on the page when rendered.
If your component's code calls a Wix Javascript SDK API, render the component and manually mock the API.
The following example demonstrates how to mock the Dashboard API's showToast()
method.
If your application interacts with a backend, mock those interactions using Vitest.
For example, if you have a page that calls the CRM backend to retrieve user contacts:
You would mock the backend interactions with the API using vitest
as follows: