Writing Unit Tests with Vitest

All versions of Nextbase Starter Kit come with Vitest installed. Vitest is a lightweight and fast testing framework that allows you to write unit tests for your application.

Configuration

Vitest is configured in the vitest.config.ts file.

vitest.config.ts
import { defineConfig } from 'vitest/config';
import react from '@vitejs/plugin-react';
import path from 'path';
 
// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()],
  test: {
    environment: 'jsdom',
  },
  // path alias
  resolve: {
    alias: {
      '@': path.resolve(__dirname, './src'),
    },
  },
});

As you can see, the configuration file is quite simple. You can customize it according to your needs.

Running tests

Vitest runs in NODE_ENV=test mode. It also relies on .env.test for environment variables.

Running Vitest

yarn test:unit

Writing tests

All the test cases are written in the tests folder.

Helper Function Test case example

This is an example of a test case for a helper function.

tests/helpers.test.ts
import { expect, test } from 'vitest';
import { toDateTime } from './helpers';
 
test('helpers: toDateTime should return a date object', () => {
  const date = new Date();
  const dateObject = toDateTime(date.getTime());
  expect(dateObject).toBeInstanceOf(Date);
});

Using Vitest with GitHub Actions

You can easily integrate Vitest with GitHub Actions to run your tests automatically on every push or pull request. Here is a basic example of a GitHub Actions workflow:

.github/workflows/test.yml
name: Test
 
on: [push, pull_request]
 
jobs:
test:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v2
 
- name: Use Node.js
uses: actions/setup-node@v2
with:
node-version: 16
 
- name: Install dependencies
run: yarn install
 
- name: Run tests
run: yarn test

Most SaaS solo developers or small teams write integration tests more, hence we only added Vitest setup and a dummy test case, but you can update the test suite as needed.