You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native中Realm快照测试报错:同一线程已打开不同Schema的Realm

React Native + Realm 快照测试问题排查

背景

开发了一款基于React Native和Realm数据库的应用,手动测试无任何异常。

Realm单元测试正常

编写的Realm数据库相关单元测试均可通过,例如创建记录的测试:

test("Create record in example table", () => {
    realm.write(() => {
        realm.create("ExampleTable", { "id": 1, "name": "Example", "notes": "Example Notes" });
    });
    const exampleRecord = realm.objects("ExampleTable")[0];
    expect(exampleRecord.id).toBe(1);
    expect(exampleRecord.name).toBe("Example");
    expect(exampleRecord.notes).toBe("Example Notes");
});

快照测试失败及报错信息

为页面编写的快照测试全部失败,出现两类错误:

错误1:Realm实例冲突

Realm at path '/home/runner/work/app-name/app-name/default.realm' already opened on current thread with different schema.

尝试在测试文件的beforeEach()、afterEach()中添加jest.clearAllMocks()、Realm.delete()等操作,均无法解决。排查资料怀疑是测试并行执行导致,但未找到有效控制测试单独运行的方法。

错误2:组件渲染异常

● Console
    console.error
      The above error occurred in the <CreateWorkout> component:
          
          at CreateWorkout (/home/runner/work/fitness-logger/fitness-logger/app/screens/create-workout/create-workout.js:10:63)
      

      113 |     const snapshotJSON = snapshot.toJSON();
      114 |     expect(snapshotJSON).toMatchSnapshot();
    > 115 |     snapshot.unmount();
          |              ^

当前使用的测试命令为:

npx jest --runInBand --detectOpenHandles --forceExit

Mock Realm的尝试与问题

经调研,快照测试涉及的页面会调用Realm相关函数,需Mock Realm才能正常执行。在测试文件中编写了如下Mock代码:

jest.mock("realm", () => {
    const mockObjects = jest.fn(() => {
        const results = [];
        results.filtered = jest.fn(() => { return results; });
        return results;
    });
    function MockRealm() {
        return {
            "objects": mockObjects,
            "write": jest.fn(),
            "create": jest.fn(),
            "deleteAll": jest.fn(),
            "close": jest.fn(),
            "addListener": jest.fn(),
            "removeListener": jest.fn(),
        };
    }
    
    MockRealm.open = jest.fn();
    MockRealm.schema = [
        {
            "name": "Table",
            "properties": {
                "id": "int",
                "property": "string",
            },
            "primaryKey": "id",
        }
    ];
    MockRealm.deleteRealmIfMigrationNeeded = true;
    return MockRealm;
});

这段代码可避免测试直接失败,但会触发页面代码中try catch块的错误:Failed to get data from schema。若将该Mock代码移至__mocks__目录下的单独文件中,测试会直接失败。

内容的提问来源于stack exchange,提问作者user27793975

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 17:16:14