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

使用Jest测试Expo React Native应用时遭遇SQLite错误

解决Expo React Native Jest测试中expo-sqlite的TypeError问题

当使用Jest测试依赖expo-sqlite的Expo React Native应用时,由于Jest运行在Node.js环境中,无法调用expo-sqlite的原生实现,会出现TypeError: Cannot read properties of undefined (reading 'map')的错误。以下是具体解决方案:

1. 创建expo-sqlite的Jest模拟文件

在项目根目录下新建__mocks__文件夹,然后创建expo-sqlite.js文件,模拟openDatabase及相关方法的行为,避免触发原生代码:

export const openDatabase = jest.fn(() => ({
  transaction: jest.fn((callback) => {
    callback({
      executeSql: jest.fn((sql, args, successCallback) => {
        // 模拟SQL执行成功,返回空结果集
        successCallback(null, { rows: { _array: [] } });
      })
    });
  })
}));

2. 配置Jest使用模拟模块

在项目的Jest配置中(可以是package.json或jest.config.js),添加模块映射,让Jest加载我们的模拟文件而非真实的expo-sqlite:

方式一:修改package.json

"jest": {
  "preset": "jest-expo",
  "moduleNameMapper": {
    "expo-sqlite": "<rootDir>/__mocks__/expo-sqlite.js"
  }
}

方式二:使用jest.config.js

module.exports = {
  preset: 'jest-expo',
  moduleNameMapper: {
    'expo-sqlite': '<rootDir>/__mocks__/expo-sqlite.js'
  }
};

3. 优化测试代码(可选)

如果App组件包含异步初始化逻辑(比如数据库连接),可以使用waitFor确保组件渲染完成后再断言:

import React from 'react';
import renderer from 'react-test-renderer';
import { waitFor } from '@testing-library/react-native';
import App from '../App';

describe('<App />', () => {
  it('has 1 child', async () => {
    jest.useFakeTimers();
    const component = renderer.create(<App />);
    
    await waitFor(() => {
      const tree = component.toJSON();
      expect(tree.children.length).toBe(1);
    });
  });
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 18:45:37