【问题标题】:How do I mock SQLite.openDatabase using jest in expo app?如何在 expo 应用程序中使用 jest 模拟 SQLite.openDatabase?
【发布时间】:2021-03-04 21:20:43
【问题描述】:

我一直无法弄清楚如何在 react 本机应用程序中用 jest 模拟 SQLite 函数。被测代码如下所示:

//helpers/db.js
import * as SQLite from 'expo-sqlite';

let db = null;

export const init = () => {
  db = SQLite.openDatabase('places.db');
  const promise = new Promise((resolve, reject) => {
    db.transaction(tx => {
      tx.executeSql(
        'CREATE TABLE IF NOT EXISTS places (id INTEGER PRIMARY KEY NOT NULL, title TEXT NOT NULL, imageUri TEXT NOT NULL, address TEXT NOT NULL, lat REAL NOT NULL, lng REAL NOT NULL);',
        [],
        () => {
          resolve();
        },
        (_, err) => {
          reject(err);
        }
      );
    });
  });
  return promise;
};

到目前为止,我的测试代码如下所示:

//helpers.db.tests.js
import { init } from './db';
import * as SQLite from 'expo-sqlite';

test('loads exercises', async () => {
  SQLite.openDatabase = jest.fn();
  SQLite.openDatabase.mockReturnValue({ transaction: () => {} })
  await init()
  expect(SQLite.openDatabase).toBeCalledWith(expect.anything());
});

我目前收到一个错误:SQLite.openDatabase.mockReturnValue 不是函数。

我正在使用 expo 39.0.2 和 expo-sqlite 8.4.0。

【问题讨论】:

    标签: react-native sqlite jestjs expo


    【解决方案1】:

    这并不能直接回答您的问题,而是一种解决方法。

    我有一个包含 SQLite 函数的 repository.ts 文件

    const db = SQLite.openDatabase('db.evready');
    
    export const createDatabase = () => {
      db.transaction(...
    

    然后我在我的测试中像这样模拟:

    jest.mock('../src/repository');
    
    it('renders correctly', () => {
      renderer.create(<App />);
    
      jest.runOnlyPendingTimers();
    });
    

    【讨论】:

      猜你喜欢
      • 2018-04-28
      • 1970-01-01
      • 2021-11-16
      • 2023-02-02
      • 2021-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-05
      相关资源
      最近更新 更多