LoginSignup
3
1

More than 1 year has passed since last update.

軽くVitest + Typescript + React触ってみた

Last updated at Posted at 2022-08-25

vitest

概要

viteベースのテストライブラリーのvitestが素早いとのことで、本当か試してみました

Installation and setup

viteでプロジェクト作成

$ yarn create vite my-app --template react-ts

vitest導入

$ yarn add -D vitest jsdom @testing-library/react @testing-library/user-event @testing-library/jest-dom

vite.config.tsを設定

/// <reference types="vitest" />

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

// https://vitejs.dev/config/
export default defineConfig({
  ...
  test: {
    environment: 'jsdom',
    setupFiles: 'src/vitest.setup.ts'
  }
})

vitest.setup.tsでは、@testing-library/jest-dom などをimportしておく

テストを書く

基本的なことから

const add = (a: number, b:number) => a + b

describe('test add()', () => {
  it("1 + 2 = 3", () => {
    expect(add(1, 2)).toBe(3)
  })
})

コンポーネントのテスト

import { render, screen } from '@testing-library/react'

const Title = ({ title }: TitleProps) => {
  return (
    <div>{title}</div>
  )
}

test('Rendering test: Title', () => {
  const title = 'Let\'s test with vitest!'

  render(<Title title={title} />)

  expect(screen.getByText(title)).toBeInTheDocument()
})

クリックイベントの違い

import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import App from '.'

describe('Component test: App', () => {
  test('click count should increment count', async () => {
    render(<App />)
    expect(screen.findByText(/count is 0/i))

    userEvent.click(screen.getByRole('button')))

    expect(await screen.findByText(/count is 1/i)).not.toBeEmptyDOMElement()
    screen.debug()
  })
})

happy-domの方が軽かった

https://github.com/capricorn86/happy-dom

jsdomより早いらしいので、happy-domの導入方法

vite.config.tsを修正

...
  test: {
    environment: 'happy-dom',
...

@testing-library/user-event のバージョン上げで、参考記事に書いているような不具合は解消した模様

スピードテスト

Vitest(happy-dom)

スクリーンショット 2022-08-25 16.33.39.png

Vitest(jsdom)

スクリーンショット 2022-08-25 16.41.09.png

Jest

スクリーンショット 2022-08-25 16.33.51.png

あんまし大したケースを積んでないので厳正な比較になってるかわかりませんが、スケールしてみながら比較するのもありかもです

参考

テストするためのプロジェクトを作る時に参考にしたもの

Vite + React + TypeScript に テスト環境 Vitest をステップbyステップで作る

あたらしいテストフレームワークVitestをReactで試してみた | DevelopersIO

troubleshootingに役立った記事
https://dev.to/mbarzeev/from-jest-to-vitest-migration-and-benchmark-23pl

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1