56
61

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[React] フロントエンドのテストって何するの?

Last updated at Posted at 2021-06-28
Page 1 of 16

テストってなんで書くの?


こんな悩みはありませんか?

  • 書いたコードに予期せぬバグがあるのではと心配になり、夜も眠れない
  • 変更後に致命的なバグが突然発生する悪い夢にうなされる

テストの目的

  • 「想定通りに動くのか」を担保するため
  • 開発者自身のため
  • 変更に強い仕様書をつくる

テストってどうやってを書くの?


Testing Torophy

  • JSテスト界の大御所Kent.Cが提唱するテストのコンセプト
  • 体積が大きいところほど重要であるとしている(ここではIntegrationが最も大きい)

トレードオフの発生

  • テストの実行スピード
  • 工数
  • カバレッジ

Kent.Cの方針

Kent.Cがtesting-libraryのドキュメント内で言っていたこと。
  • テストはアプリケーションの利用方法に似ているほど信頼性が得られるのさ
  • 実装の詳細をテストしないことを勧めるよ(実施してもいいけどね)

テストって何を書けばいいの?


実際に書いてみる

テスト対象: Incrementボタンを押すと、数字が1増えて表示される。(初期表示は0)

export function Counter() {
  const [count, setCount] = useState(0);
  const increment() {
    setCount(count + 1);
  }
  return (
    <>
      <div>Number: {count}</div>
      <div>
        <button onClick={increment}>Increment</button>
      </div>
    </>
  )
}

実際に書いてみる

仕様ライブラリ: Jest, react-testing-library
テスト内容:

  • 初期表示はNumber: 0
  • Increamentボタンを押すと数字が1つ増える
import { fireEvent, render, screen } from "@testing-library/react"
import { Counter } from "./"

describe("Counter", () => {
  test("render", () => {
    render(<Counter />)
    expect(screen.getByText('Number: 0')).toBeInTheDocument();
  })
  test("increment", () => {
    render(<Counter />)
    const button = screen.getByText("Increment")
    fireEvent.click(button)
    screen.getByText("Number: 1")
  })
})

なるほどこれは仕様書になる...!


Reactで優先的に書くべきテスト

  • ロジックがあるor少し複雑なUIコンポーネントのIntegration Test
  • Custom Hooksなどの切り出されたロジックのUnit Test

ロジックが複雑でバグが出やすそう...
ここが壊れたらヤバい!不安で夜も眠れない...
そんな不安を解消してくれそうな部分からテストを書きましょう。


はじめてテストをやってみて


感想・気づき

  • サーバーサイドのテストとはまた違った難しさがある
  • Integration Testをしっかり書けば仕様書になる
  • E2EテストのCypressも触ってみたい

ご清聴ありがとうございました


「複業クラウド」について

弊社Another worksでは複業マッチングプラットフォーム「複業クラウド」を開発しています!

▼複業でスキルを活かしてみませんか?複業クラウドの登録はこちら!
https://talent.aw-anotherworks.com/?login_type=none

56
61
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
56
61

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?