React Native应用测试无法运行如何解决?遵循官方文档仍遇问题
Hey Kathy, sorry to hear you're hitting snags with testing your Expo React Native app—running the app smoothly but failing tests is such a frustrating disconnect! Let's walk through the most common fixes that usually resolve this:
Expo doesn't ship with all test tools out of the box, so first double-check you have these dev dependencies set up:
npm install --save-dev jest jest-expo @testing-library/react-native @testing-library/jest-native
jest-expowraps Jest to work seamlessly with Expo's environment (like handling native modules and Expo-specific APIs)@testing-library/react-nativegives you intuitive tools to write component tests@testing-library/jest-nativeadds useful matchers tailored for React Native elements
Next, ensure your project is configured to use the Expo preset. You can add this directly to your package.json:
"scripts": { "test": "jest" }, "jest": { "preset": "jest-expo", "setupFilesAfterEnv": [ "@testing-library/jest-native/extend-expect" ] }
Or create a separate jest.config.js file for cleaner separation:
module.exports = { preset: 'jest-expo', setupFilesAfterEnv: [ '@testing-library/jest-native/extend-expect', ], };
This tells Jest to use Expo's preset and load the extra React Native-specific matchers.
Sometimes the issue is with your test code itself, not the setup. Create a minimal test file (like __tests__/App-test.js) to validate the setup works:
import React from 'react'; import { render, screen } from '@testing-library/react-native'; import App from '../App'; test('renders basic app text', () => { render(<App />); // Replace this text with something that actually appears in your App component expect(screen.getByText('Welcome to React Native!')).toBeVisible(); });
Run npm test after creating this—if it passes, your setup is solid, and the problem lies with your original test code.
Cached files often cause weird test failures even when everything else looks right. Run these commands:
- Clear Jest's cache:
jest --clearCache - Restart Expo with a fresh cache:
expo start -c
Then try running your tests again.
If your app uses Expo modules like Camera, Location, or Permissions, you'll need to mock them in your tests since Jest can't run native code. For example, if you're using Expo Camera:
jest.mock('expo-camera', () => ({ Camera: jest.fn(() => null), requestCameraPermissionsAsync: jest.fn(() => Promise.resolve({ granted: true })), }));
jest-expo mocks some common APIs automatically, but niche modules might need manual mocking.
If you're still getting errors after trying these steps, sharing the exact error message would help narrow things down further—but these fixes resolve 90% of the "tests won't run" issues I've seen with Expo + React Native.
内容的提问来源于stack exchange,提问作者Kathy

