freks blog

about

RemixでVitestを使う

created: 2025-03-19
おすすめ記事: 出会ってよかったプログラマー本

RemixでVitestを導入してみました

npx create-remix@latest

で作った、vite 6.2.2 で試しています

vitestを動かす

Getting Started | Guide | Vitest をみて vitest を入れる

npm install --save-dev vitest

package.json

"scripts": {
  "test": "vitest"
}

を追加しておいて

vitest.config.ts の設定ファイルを用意

import { defineConfig } from 'vitest/config'

export default defineConfig({
  test: {
    globals: true
  },
})

import { expect, test } from 'vitest' のimportが省略できます

TypeScriptにも vitest を読み込ませたいので tsconfig.json

{
  "compilerOptions": {
    "types": ["vitest/globals"]
  }
}

を追加

これで sample.test.ts を作って

test('adds 1 + 2 to equal 3', () => {
  expect(1 + 2).toBe(3)
})

npm run test でテストが走ります

React componentをvitestで動かす

Button componentを作ってテストしてみます

export function Buttion() {
  return <button>Click me</button>;
}

このままではvitestでReactを動かせないので、@testing-library/react を使います

React Testing Library | Testing Library

npm install --save-dev @testing-library/react @testing-library/dom @types/react @types/react-dom

dom操作をするために
Setup | Testing Library
を見て

npm install --save-dev jsdom global-jsdom

vitest.config.ts の設定ファイルに environment: 'jsdom' を追加

import { defineConfig } from 'vitest/config'

export default defineConfig({
  test: {
    globals: true,
    environment: 'jsdom',
  },
})

これで vitest でdom操作できるようになります

Button componentのテストを用意します

import { render, screen } from '@testing-library/react';
import { Buttion } from './Button';

describe('Button', () => {
  test('renders button with correct text', () => {
    render(<Buttion />);
    const button = screen.getByRole('button');
    expect(button.textContent).toBe('Click me');
  });
});

テストを実行して通ればOKです

まとめ

一気に確認できるドキュメントがなくて調べながらやりました

PR

スーパーユーザーなら知っておくべきLinuxシステムの仕組み

スーパーユーザーなら知っておくべきLinuxシステムの仕組み

このリンクは、アフィリエイトリンクです


Amazonのアソシエイトとして、blog.freks.jp は適格販売により収入を得ています。
This site is managed by freks