React Native项目中Jest执行完成后无法退出,检测显示为测试相关库本身问题
Hey there, let's work through this Jest exit issue you're hitting. Based on your dependency versions and setup, here are the most actionable fixes to try:
1. Align All Jest-Related Dependency Versions
The biggest red flag here is your mixed Jest versions: you're running Jest 28.1.0, but babel-jest and jest-circus are stuck on 26.6.3. Version mismatches like this are a top cause of unexpected handle leaks and exit failures in React Native projects.
Here's how to fix it:
- Open your
package.jsonand update these dependencies to match your Jest version (28.1.0):{ "babel-jest": "^28.1.0", "jest-circus": "^28.1.0", "eslint-plugin-jest": "^27.0.0" // Upgrade to a version compatible with Jest 28 } - Run
npm installoryarn installto sync the versions across your project.
This is the most critical step—don't skip it!
2. Add a Proper Jest Configuration File
Since you don't have a Jest config file yet, creating one will enforce proper cleanup and environment settings. Make a jest.config.js file in your project root with these settings:
module.exports = { preset: 'react-native', testEnvironment: 'node', testRunner: 'jest-circus/runner', // Ensure testing-library cleans up components/listeners after each test setupFilesAfterEnv: ['@testing-library/react-native/cleanup-after-each'], // Optional: Use as a temporary fallback if leaks persist after version fixes // forceExit: true, detectOpenHandles: true, };
The setupFilesAfterEnv line ensures @testing-library/react-native cleans up mounted components or lingering event listeners after every test, which directly prevents open handle leaks.
3. Manually Clean Up Async/Subscription Resources
Even with automated cleanup, some edge cases can leave open handles:
- Timers: Use
jest.useFakeTimers()at the start of your test block andjest.clearAllTimers()in anafterEachhook to clean up unprocessed timers. - Subscriptions: Add an
afterEachblock to unsubscribe from custom event emitters, Redux store listeners, or other persistent subscriptions:afterEach(() => { myCustomEmitter.removeAllListeners(); // Add any other manual cleanup here });
4. Consider Upgrading React Native (Optional)
React Native 66.4 is a relatively old version, and it may have limited compatibility with Jest 28. If the above steps don't resolve the issue, upgrading to a more recent stable version (like 0.68.x or higher) can improve Jest integration and fix underlying compatibility bugs.
Start with step 1 first—version alignment almost always fixes this kind of exit issue. If you still see the error after that, move to adding the config file and checking for leftover resources in your tests.
内容的提问来源于stack exchange,提问作者dash

