如何在运行Jest时阻止生成Realm JS相关文件?
Hey there, let's fix this at the root—since you're already using workarounds to exclude the files, here's how to stop them from being created in the first place when running Jest tests:
1. Force Realm to Use In-Memory Databases for Tests
The core issue is that Realm defaults to creating persistent disk-based database files in your project root during tests. Switching to an in-memory configuration skips writing any files to disk entirely, which is ideal for testing scenarios.
Here's how to set this up globally for all your tests:
- Create a Jest setup file (e.g.,
jest.setup.js) in your project root:import Realm from 'realm'; // Override Realm's default configuration to use in-memory storage for tests Realm.defaultConfiguration = { ...Realm.defaultConfiguration, inMemory: true, // Optional: Add this to avoid migration-related issues in test environments deleteRealmIfMigrationNeeded: true, }; - Update your
jest.config.jsto load this setup file before tests run:module.exports = { setupFiles: ['./jest.setup.js'], // Keep your existing Jest configuration (moduleFileExtensions, transform, etc.) here };
This will make every Realm instance created during tests use in-memory storage, so no .realm files, lock files, or management folders will be generated at all.
2. Per-Test Cleanup (If You Need Persistent Storage for Specific Tests)
If some tests require actual disk storage (uncommon for unit tests), you can explicitly use a temporary path and clean up after each test:
import Realm from 'realm'; import fs from 'fs'; import path from 'path'; describe('Realm Persistence Tests', () => { let realm; const testRealmPath = path.join(__dirname, 'test-temp.realm'); beforeEach(() => { // Create Realm with a temporary, isolated path realm = new Realm({ schema: [YourDataSchema], path: testRealmPath, }); }); afterEach(() => { if (realm) { realm.close(); // Delete the temporary Realm files Realm.deleteFile({ path: testRealmPath }); // Clean up the associated management folder if it exists const managementDir = `${testRealmPath}.management`; if (fs.existsSync(managementDir)) { fs.rmdirSync(managementDir, { recursive: true }); } } }); // Your test cases go here... });
3. Double-Check Jest Configuration
Ensure your Jest setup isn't accidentally pointing to your project root as a working directory (it does this by default, but the in-memory fix should override this behavior). If you have custom rootDir settings in jest.config.js, confirm they don't cause Realm to write files to your app's source directory.
The in-memory approach is the most reliable solution here—it eliminates the need for post-test cleanup or exclusion rules entirely, which should resolve your Android build freeze issue for good.
内容的提问来源于stack exchange,提问作者Zidail

