概要

React.js の話をしようぜ!

このシリーズの初回に、 utils のベースを作ったよな。

ここで src/utils/formatDate.ts を作ったわけだが、ユニットテストを作っていないじゃん! 2025年のプログラムにユニットテストは必須だ。追加しておこう。

 

ユニットテストのベースを追加する

ユニットテストのパッケージとしては Vitest を選ぶ。なんでかってーと、このスターターキット自体を立ち上げるときに yarn create vite my-react -- -template react-swc-ts を使っており、 Vite をベースにしたプロジェクトになっているからだね。

yarn add -D vitest
# Vitest をインストール。
# src/utils/formatDate.test.ts を作成
echo 'import { describe, it, expect } from "vitest"
import formatDate from "./formatDate"

// Vitest doc: https://vitest.dev/api/

describe("formatDate", () => {
  it("should format date as `Month day, year`", () => {
    const date = new Date("2023-03-15")
    const result = formatDate(date)
    expect(result).toBe("March 15, 2023")
  })
})' > src/utils/formatDate.test.ts
# 使ってみる。
# run 無し: watch mode
# run 有り: いつものふつーの
yarn run vitest run
# 出力↓
# $ ...my-react/node_modules/.bin/vitest run
# ...中略
#  ✓ src/utils/formatDate.test.ts (1 test) 9ms
#    ✓ formatDate > should format date as `Month day, year`
#
#  Test Files  1 passed (1)
#       Tests  1 passed (1)
# ...中略
# Done in 0.71s.

 

おしまい

うむ、完璧だな。

でも、インストールせずとも、組み込みの unittest 機能を持っている Python ちゃんってもっと完璧だな。 (Pythonista の余計な一言)