📖

React Navigation テストエラーの解決方法

2023/05/12に公開

はじめに

この記事では、React NativeとReact Navigationを使用したプロジェクトでJestを使ったテストを行う際に発生するエラーの解決方法を記載します。

前提条件:

  • React Nativeを使用している
  • React Navigationを使用している
  • Jestを使用している

エラーメッセージは以下のようになります。

 FAIL  __tests__/App-test.tsx
  ● Test suite failed to run

    Jest encountered an unexpected token

    Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

    Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

    By default "node_modules" folder is ignored by transformers.

    Here's what you can do:
     • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
     • If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
     • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
     • If you need a custom transformation specify a "transform" option in your config.
     • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

    You'll find more details and examples of these config options in the docs:
    https://jestjs.io/docs/configuration
    For information about custom transformations, see:
    https://jestjs.io/docs/code-transformation

目標: React Navigationコンポーネントのテストが通る

1.必要なパッケージをインストール

ターミナル
yarn add -D react-native-reanimated react-native-gesture-handler

2.App-test.tsxを修正

__tests__/App-test.tsx
import 'react-native';
import React from 'react';
import App from '../src/App';

// Note: test renderer must be required after react-native.
import renderer from 'react-test-renderer';

const sleep = (ms: number) => new Promise((resolve) => setTimeout(() => resolve(true), ms));

jest.mock('react-native/Libraries/Animated/NativeAnimatedHelper');

it('renders correctly', async () => {
  const tree = renderer.create(<App />).toJSON();
  expect(tree).toMatchSnapshot();
  await sleep(10);
});

3.setup.tsファイルを追加

jest/setup.ts
import 'react-native-gesture-handler/jestSetup';

jest.mock('react-native-reanimated', () => {
  const Reanimated = require('react-native-reanimated/mock');

  // The mock for `call` immediately calls the callback which is incorrect
  // So we override it with a no-op
  Reanimated.default.call = () => {};

  return Reanimated;
});

// Silence the warning: Animated: `useNativeDriver` is not supported because the native animated module is missing

// 公式ドキュメントとは記述を変えています
jest.mock('react-native/Libraries/Animated/NativeAnimatedHelper');

4.package.jsonに追記

package.json
{
  "jest": {
    "preset": "react-native",
    "setupFiles": [
      "<rootDir>/jest/setup.ts"
    ],
    "moduleFileExtensions": [
      "ts",
      "tsx",
      "js",
      "jsx",
      "json",
      "node"
    ],
    "transformIgnorePatterns": [
      "node_modules/(?!react-native|@react-native|@react-navigation)"
    ]
  },
}

必要なパッケージ

https://github.com/software-mansion/react-native-reanimated
https://github.com/software-mansion/react-native-gesture-handler

参考記事

https://source--react-navigation-docs.netlify.app/docs/testing/
https://stackoverflow.com/a/58260761
https://github.com/react-navigation/react-navigation/issues/10943#issuecomment-1294577528

Discussion