Create a react app using Vite - Part 3

vinomanick

Vinodh Kumar

Posted on August 15, 2023

Create a react app using Vite - Part 3

Unit testing

Vitest is a new framework that is gaining popularity with the developers who are using Vite. Let's see how to configure it for our project.

  • Install the necessary packages
pnpm add -D vitest @vitest/coverage-v8
pnpm add -D @testing-library/react jsdom @testing-library/jest-dom
Enter fullscreen mode Exit fullscreen mode
  • Create the src/setupTests.ts file and update it with the below content.
 touch src/setupTests.ts
Enter fullscreen mode Exit fullscreen mode
// This import will add the DOM related assertions support to the expect statement.
import { beforeAll, beforeEach, afterAll, afterEach } from 'vitest'

import '@testing-library/jest-dom/vitest'

beforeAll(() => {
  // Add your global beforeAll logics
})

beforeEach(() => {
  // Add your globalbeforeEach logics
})

afterAll(() => {
  // Add your global afterAll logics
})

afterEach(() => {
  // Add your global afterEach logics
})
Enter fullscreen mode Exit fullscreen mode
  • Configure the test environment in the vite.config.ts.
    • Change the import path of the defineConfig from vite to vitest/config.
import { defineConfig } from 'vitest/config';

export default defineConfig({
  ...,
  test: {
    environment: 'jsdom',
    setupFiles: ['src/setupTests.ts'],
    coverage: {
      exclude: ['*.config.*', '*.d.ts'],
    },
  },
});

Enter fullscreen mode Exit fullscreen mode
  • Create a test file for the app component and update it like the below,
touch src/App.test.tsx
Enter fullscreen mode Exit fullscreen mode
import { render, screen } from '@testing-library/react'
import { App } from './App'
import { describe, expect, test } from 'vitest'

describe('Component | App', () => {
  test('should render the app component', () => {
    render(<App />)
    expect(screen.getByText('Rendered from react app')).toBeInTheDocument()
  })
})
Enter fullscreen mode Exit fullscreen mode
  • Update the package scripts for running tests
npm pkg set scripts.test="vitest"
npm pkg set scripts.test:cov="vitest run --coverage"
Enter fullscreen mode Exit fullscreen mode
  • Run the tests
  pnpm test
Enter fullscreen mode Exit fullscreen mode
  • To run a particular test use the -t param.
  pnpm test -- -t "add"
Enter fullscreen mode Exit fullscreen mode

Sample repo

The code for this series is hosted in Github here.

Please take a look at the Github repo and let me know your feedback, and queries in the comments section.

💖 💪 🙅 🚩
vinomanick
Vinodh Kumar

Posted on August 15, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related