LoginSignup
1
1

More than 3 years have passed since last update.

CRA(v3.4.1)のReact Testing Libraryで最初に対処すること

Posted at

概要

CRA(create-react-app)にはテストフレームワークが最初から入っており、テストコードファイルも最初からミニマムで用意してくれています。
試しにサクッとテスト実装を、、、と思ったら冒頭からエラーで手間取ってしまったので、対処結果を書いてみます。

前提

  • create-react-app : 3.4.1
    • テンプレートはtypescriptです
    • create-react-app [プロジェクト名] --template typescript
  • react-scripts : 3.4.1
  • @testing-library/jest-dom : ^4.2.4
  • @testing-library/react : ^9.3.2

エラー:「@testing-library/react"' has no exported member 'screen'」

コード

App.test.tsx
import { render, screen } from '@testing-library/react';

エラー

error
"@testing-library/react"' has no exported member 'screen'"

対処

console
yarn remove @testing-library/react @testing-library/jest-dom && yarn add @testing-library/react @testing-library/jest-dom

参考

https://github.com/testing-library/react-testing-library/issues/610#issuecomment-614982674
yarn upgradeでは他のモジュールバージョンも上がって依存関係が解消されないようで、対象モジュールのみを再インストールする必要があるようです。

エラー:「MutationObserver is not a constructor」

コード

App.test.tsx
const result = await screen.findByText('xxx', undefined, {timeout: 3000});

エラー

error
"MutationObserver is not a constructor"

対処

package.json
- "test": "react-scripts test",
+ "test": "react-scripts test --env=jest-environment-jsdom-fourteen",

参考

感想

  • 新しいライブラリを触った際、文法が正しそうなのにエラーが出ると「まずはTypeScriptの@type~が足りないのかも」など、つい疑ってしまうのですが、ちゃんとissueとか探るのも大事ですね。
1
1
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
1
1