はじめに
以前にcreate-react-appで作成したReactアプリをテストしてみるというJestとEnzymeを使ってテストを行う記事を書きましたが、
今回は、以下の記事を参考にしてReact Testing Libraryを使ってみました。
本記事は実際に手を動かしてみた感想ですので、詳しくは参考記事をご覧ください。
では手を動かしていきます。
テスト実行時のエラー
記事通りに手を動かしていくと、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
上記の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
はなるべく避けるという知見を得る事ができました。
これは、クエリというもので公式ドキュメントのガイドにも優先順位が書いてありました。
おわりに
react-testing-library
はcreate-react-app
の場合最初から導入されているので、すぐに始める事ができます。
テストを書いてみるのは2回目でしたが、独自のヘルパー関数を作る部分の理解が足りずもう少し勉強が必要だと感じました。
自分が実際にやった物はこちらのリポジトリにあげていこうと思います。