React Native测试环境搭建与TDD/BDD配置及语法错误解决求助
Hey there, let's tackle this problem step by step—first fixing that annoying syntax error, then getting your full TDD/BDD environment set up for React Native 0.62.
First: Fix the "Unexpected token 'export'" Error
That error happens because Jest doesn't automatically transpile code in node_modules by default, but react-navigation (and its dependencies) use ES module syntax (export * from ...) that your current setup isn't processing. Here's how to fix it:
Update your Jest config
Open yourpackage.json(or create ajest.config.jsif you prefer) and modify thetransformIgnorePatternsto tell Jest to transpilereact-navigationand its core packages. Add this under thejestfield:"jest": { "preset": "react-native", "transformIgnorePatterns": [ "node_modules/(?!(react-native|@react-navigation|@react-navigation/core|@react-navigation/native|@react-native-community)/)" ] }The
?!means "exclude these packages from the ignore list"—so Jest will run Babel on them instead of skipping.Verify your Babel config
Make sure yourbabel.config.jsuses the official Metro preset for React Native (required for 0.60+):module.exports = { presets: ['module:metro-react-native-babel-preset'], };This preset handles transpiling ES modules to CommonJS, which Jest understands.
Clear Jest's cache
Old cached builds can mess up new configs. Run this command to reset:npm test -- --clearCacheNow try running
npm testagain—that syntax error should be gone.
Next: Build a Complete TDD/BDD Environment
Let's cover both component testing (for unit/TDD) and UI testing (for end-to-end BDD).
1. Component Testing (TDD with Jest + React Testing Library)
React Testing Library is the modern, user-centric choice for component tests—it aligns perfectly with TDD by focusing on what users see and do, not internal component logic.
Setup Steps:
- Install dependencies:
npm install --save-dev @testing-library/react-native @testing-library/jest-native - Extend Jest with Testing Library matchers:
Add this to your Jest config (inpackage.jsonorjest.config.js):
This gives you useful matchers like"jest": { // ... existing config "setupFilesAfterEnv": ["@testing-library/jest-native/extend-expect"] }.toBeVisible()or.toHaveTextContent().
Example TDD Component Test:
Let's say you're building a CustomButton component. First write a failing test, then build the component to pass it:
import React from 'react'; import { render, fireEvent } from '@testing-library/react-native'; import CustomButton from '../CustomButton'; describe('CustomButton', () => { it('triggers the onPress callback when tapped', () => { // Arrange: Create a mock function const onPressMock = jest.fn(); // Act: Render the button and simulate a tap const { getByText } = render( <CustomButton onPress={onPressMock} title="Tap Me" /> ); fireEvent.press(getByText('Tap Me')); // Assert: Verify the mock was called expect(onPressMock).toHaveBeenCalledTimes(1); }); });
This follows TDD: Red (test fails), Green (write component code to pass), Refactor (clean up code without breaking tests).
2. UI Testing (BDD with Detox)
Detox is React Native's go-to end-to-end UI testing tool, and it supports BDD-style tests that mimic real user flows.
Setup Steps:
- Install Detox and its dependencies:
npm install --save-dev detox @types/detox detox-cli - Configure Detox in
package.json:
Add this block (replaceProjectNamewith your app's name, and adjust device types as needed):"detox": { "test-runner": "jest", "configurations": { "ios.sim.debug": { "binaryPath": "ios/build/Build/Products/Debug-iphonesimulator/ProjectName.app", "build": "xcodebuild -workspace ios/ProjectName.xcworkspace -scheme ProjectName -configuration Debug -sdk iphonesimulator -derivedDataPath ios/build", "type": "ios.simulator", "device": { "type": "iPhone 11" } }, "android.emu.debug": { "binaryPath": "android/app/build/outputs/apk/debug/app-debug.apk", "build": "cd android && ./gradlew assembleDebug assembleAndroidTest -DtestBuildType=debug", "type": "android.emulator", "device": { "avdName": "Pixel_3a_API_30_x86" } } } } - Initialize Detox test files:
detox init -r jest
Example BDD UI Test:
Write tests that cover core user journeys in e2e/firstTest.spec.js:
describe('App Flow', () => { beforeAll(async () => { await device.launchApp(); }); beforeEach(async () => { await device.reloadReactNative(); }); it('shows the welcome screen on launch', async () => { await expect(element(by.text('Welcome to My App!'))).toBeVisible(); }); it('navigates to the profile screen when the profile button is tapped', async () => { await element(by.id('profile-button')).tap(); await expect(element(by.text('My Profile'))).toBeVisible(); }); });
Run UI Tests:
# For iOS detox build -c ios.sim.debug detox test -c ios.sim.debug # For Android detox build -c android.emu.debug detox test -c android.emu.debug
Quick Note on Your TDD Question
You’re right that TDD is a mainstream practice, but React Native doesn’t bundle a default test environment because there’s no one-size-fits-all solution—teams might prefer different tools (e.g., Enzyme instead of Testing Library, Appium instead of Detox). The official presets give you a starting point, but you get to tailor the setup to your workflow.
Pro Tips for TDD/BDD Success:
- Component Tests: Focus on user behavior, not internal state. Test what the user sees and interacts with, not how the component manages its data.
- UI Tests: Cover critical user flows (login, checkout, navigation) but leave detailed component logic to unit tests—UI tests are slower and more brittle.
- CI Integration: Add your tests to a CI pipeline (like GitHub Actions) to run them automatically on every commit, catching issues early.
内容的提问来源于stack exchange,提问作者Marcelo Ribeiro

