0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Next.jsプロジェクトにVitestをyarnで導入する

0
Posted at

Next.jsプロジェクトにVitestを導入して簡単なテストの書き方をまとめます。

環境

"next": "^14.0.4",
"node": "20.10.0",
"yarn": "4.9.2"
"TypeScript":"5.8.3"

インストール(yarn)

yarn add -D vitest 

package.jsonにスクリプトを追加

{
  "scripts": {
    "test": "vitest",
    "test:watch": "vitest --watch"
  }
}

簡単なテストを書いてみる

sum.js
export function sum(a, b) {
  return a + b
}
sum.test.js
import { expect, test } from 'vitest'
import { sum } from './sum.ts'

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

デフォルトでは、テストのファイル名には「.test.」または「.spec.」が含まれている必要があるとのこと。

使用している関数の簡単な説明

test()

テストケースを定義する関数です。

test('テストの説明', () => {
  // テスト内容
})

第一引数にテストの説明文、第二引数に実行する処理を書く

expect()

値を検証するための関数です。

expect().toBe(期待値)

toBe()

実際の値と期待値が「完全一致」するかを判定します。

expect(sum(1, 2)).toBe(3)

テストの実行方法

yarn test

ウォッチモードでの起動
以下コマンドで実行するとコードを変更して保存するたびにテストが実行される

yarn test:watch

公式が推奨してる拡張機能

まとめ

フロントエンドでもユニットテストを書こうと試行錯誤しています。
テストコードを書いた経験があればすぐにキャッチアップできるかなと思いました。
これからもっと触っていこうと思います。

参考

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?