坂本研のゼミ室

react-testing-libraryでテストをやってみて

はじめに

以前にcreate-react-appで作成したReactアプリをテストしてみるというJestとEnzymeを使ってテストを行う記事を書きましたが、

今回は、以下の記事を参考にしてReact Testing Libraryを使ってみました。

本記事は実際に手を動かしてみた感想ですので、詳しくは参考記事をご覧ください。

www.freecodecamp.org

では手を動かしていきます。

テスト実行時のエラー

記事通りに手を動かしていくと、2. Testing DOM elements (DOM要素のテスト)の所で以下のようなエラーが出ました

  • TestElements.test.js
import React from 'react'
import { render, cleanup } from '@testing-library/react'
import { TestElements } from './TestElements'

afterEach(cleanup)

// カウンターが0に等しいか
it('should equal to 0', () => {
    const { getByTestId } = render(<TestElements />)
    expect(getByTestId('counter')).toHaveTextContent(0)
})

// ボタンが有効か無効か
it('should be disabled', () => {
    const { getByTestId } = render(<TestElements />)
    expect(getByTestId('button-down')).toBeDisabled()
})
TypeError: expect(...).toHaveTextContent is not a function

TypeError: expect(...).toBeDisabled is not a function

github.com

上記のissuesにある通りにimport "@testing-library/jest-dom/extend-expect";を追加する事で解決しました。以降同じようにやっていきます。

  • TestElements.test.js (修正後)
import React from 'react'
import { render, cleanup } from '@testing-library/react'
import { TestElements } from './TestElements'
import '@testing-library/jest-dom/extend-expect'

afterEach(cleanup)

// カウンターが0に等しいか
it('should equal to 0', () => {
    const { getByTestId } = render(<TestElements />)
    expect(getByTestId('counter')).toHaveTextContent(0)
})

// ボタンが有効か無効か
it('should be disabled', () => {
    const { getByTestId } = render(<TestElements />)
    expect(getByTestId('button-down')).toBeDisabled()
})

yarn testを実行してテストが通りました🎉

これまで、getByTestIdをなんとなく使ってきましたが以下の記事にTipsとしてgetByTestIdはなるべく避けるという知見を得る事ができました。

qiita.com

これは、クエリというもので公式ドキュメントのガイドにも優先順位が書いてありました。

testing-library.com

testing-library.com

おわりに

react-testing-librarycreate-react-appの場合最初から導入されているので、すぐに始める事ができます。

テストを書いてみるのは2回目でしたが、独自のヘルパー関数を作る部分の理解が足りずもう少し勉強が必要だと感じました。

自分が実際にやった物はこちらリポジトリにあげていこうと思います。

その他の参考文献

kentcdodds.com