跳至主要內容

設定

設定你的專案

對於大多數測試來說,React Native Testing Library API 應該可以直接使用。假設您使用 Jest 和較新版本的 React Native,那麼您在整個網站上找到的所有程式碼片段都可以正常運作,無需任何額外的設定。

自訂渲染

定義一個自訂的渲染方法通常很有用,該方法包含全域上下文供應商、資料儲存等。為了讓它在全域可用,一種方法是定義一個工具檔案,從 React Native Testing Library 重新匯出所有內容。您可以在所有匯入中將 React Native Testing Library 替換為此檔案。有關如何使您的測試工具檔案在不使用相對路徑的情況下可存取的資訊,請參閱下方

my-component.test.js
- import { render, fireEvent } from '@testing-library/react-native';
+ import { render, fireEvent } from '../test-utils';
test-utils.js
import {render} from '@testing-library/react-native'
import {ThemeProvider} from 'my-ui-lib'
import {TranslationProvider} from 'my-i18n-lib'
import defaultStrings from 'i18n/en-x-default'

const AllTheProviders = ({children}) => {
return (
<ThemeProvider theme="light">
<TranslationProvider messages={defaultStrings}>
{children}
</TranslationProvider>
</ThemeProvider>
)
}

const customRender = (ui, options) =>
render(ui, {wrapper: AllTheProviders, ...options})

// re-export everything
export * from '@testing-library/react-native'

// override render method
export {customRender as render}

使用測試工具設定 Jest

若要讓您的自訂測試檔案在 Jest 測試檔案中可存取,而無需使用相對匯入(../../test-utils),請將包含該檔案的資料夾新增到 Jest moduleDirectories 選項中。

這將使 test-utils 目錄中的所有 .js 檔案在無需 ../ 的情況下可匯入。

my-component.test.js
- import { render, fireEvent } from '../test-utils';
+ import { render, fireEvent } from 'test-utils';
jest.config.js
module.exports = {
moduleDirectories: [
'node_modules',
+ // add the directory with the test-utils.js file, for example:
+ 'utils', // a utility folder
+ __dirname, // the root directory
],
// ... other options ...
}