Jestによるテスト
React Navigationを使用してコードをテストするには、ナビゲーターで使用されるネイティブ依存関係のモックが必要になるため、いくつかの設定が必要になる場合があります。ユニットテストを記述するには、Jestを使用することをお勧めします。
ネイティブモジュールのモック化
React Navigationコンポーネントをテストできるようにするには、使用しているコンポーネントによって特定の依存関係をモック化する必要があります。
@react-navigation/drawer
を使用している場合、モックにする必要があります
react-native-reanimated
react-native-gesture-handler
@react-navigation/stack
を使用している場合、モック化する必要があります
react-native-gesture-handler
モックを追加するには、ファイルjest/setup.js
(または任意の選択したファイル名)を作成し、次のコードをその中に貼り付けます
// include this line for mocking react-native-gesture-handler
import 'react-native-gesture-handler/jestSetup';
// include this section and the NativeAnimatedHelper section for mocking react-native-reanimated
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');
その後、jest設定でこのセットアップファイルを使用する必要があります。jest.config.js
ファイルまたはpackage.json
のjest
キー内のsetupFiles
オプションの下に追加できます
{
"preset": "react-native",
"setupFiles": ["<rootDir>/jest/setup.js"]
}
setupFiles
内のファイルへのパスが正しいことを確認してください。Jestはテストを実行する前にこれらのファイルを実行するため、グローバルモックを配置するのに最適な場所です。
Jestを使用していない場合は、使用しているテストフレームワークに従って、これらのモジュールをモック化する必要があります。
テストの作成
テストを作成するには、React Native Testing Libraryをjest-native
と一緒に使用することをお勧めします。
例
import * as React from 'react';
import { screen, render, fireEvent } from '@testing-library/react-native';
import { NavigationContainer } from '@react-navigation/native';
import { RootNavigator } from './RootNavigator';
test('shows profile screen when View Profile is pressed', () => {
render(
<NavigationContainer>
<RootNavigator />
</NavigationContainer>
);
fireEvent.press(screen.getByText('View Profile'));
expect(screen.getByText('My Profile')).toBeOnTheScreen();
});
ベストプラクティス
React Navigation を使用するコンポーネントのテストを作成する際の注意点が 2 つあります。
- React Navigation をモックしないでください。その代わりに、モックを使用してテストで実際のナビゲータを使用します。
- ナビゲーションアクションを確認しないでください。その代わりに、レンダリングされた画面など、ナビゲーションの結果を確認します。