略過前往主要內容
版本:6.x

使用 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 config 中使用此設定檔。你可以將其新增至 jest.config.js 檔案中的 setupFiles 選項,或新增至 package.json 中的 jest 金鑰下方。

{
"preset": "react-native",
"setupFiles": ["<rootDir>/jest/setup.js"]
}

確認 setupFiles 中的檔案路徑是否正確。Jest 會在執行測試前執行這些檔案,所以這是放置全域性模擬的最佳位置。

如果你沒有使用 Jest,則需要根據你使用的測試架構來模擬這些模組。

撰寫測試

我們建議將 React Native Testing Libraryjest-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 的元件撰寫測試時,有幾件事需要注意:

  1. 避免模擬 React Navigation。請改在測試中使用實際的導航器。
  2. 請勿檢查導航動作。請改檢查導航的結果,例如已渲染的畫面。