Skip to content

makepath/react-vitest-examples

Repository files navigation

Vitest + React + TypeScript + Redux + MSW

This template provides a minimal setup to get React working with Vitest.

Commands

npm run test
npm run coverage

Tests

Simple components

import { describe, it, expect, beforeEach, vi } from 'vitest'
import { userEvent } from '@vitest/browser/context'
import { render } from 'vitest-browser-react'
import Button from '../Button'

describe('Button', () => {
  const mockProps = {
    label: 'Test button',
    onClick: vi.fn(),
  }

  it('renders button with label', async () => {
    const { getByText } = render(<Button {...mockProps} />)

    await expect.element(getByText('Test button')).toBeInTheDocument()
  })

  it('onClick should be called', async () => {
    vi.spyOn(mockProps, 'onClick')
    const { container } = render(<Button {...mockProps} />)

    await userEvent.click(container)
    expect(mockProps.onClick).toHaveBeenCalled()
  })
})

Testing components connected with the Redux store

import { describe, it, expect } from 'vitest'
import { renderWithProviders } from './mocks/test-utils'
import App from './App'

describe('App', () => {
  it('renders with mocked redux state and server response', async () => {
    const { getByText } = renderWithProviders(<App />)

    await expect.element(getByText('Vite + React')).toBeInTheDocument()
  })
})

Testing Redux actions and selectors

import reducer, { add, selectCount } from '../slices/counter'
import { vi, describe, it, expect, beforeEach } from 'vitest'

describe('Counter Slice', () => {
  const initialState = {
    count: 0,
  }

  beforeEach(() => {
    vi.clearAllMocks()
  })

  it('should add to count', () => {
    let currentState = reducer(initialState, add(42))
    expect(currentState.count).toEqual(42)
  })

  it('should select count', () => {
    const mockState = {
      counter: {
        count: 42,
      },
    }

    const count = selectCount(mockState)
    expect(count).toEqual(42)
  })
})

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published