How do I mock SQLite.openDatabase using jest in expo app?

Viewed 617

I have been having trouble figuring out how to mock SQLite functions with jest in a react native app. The code under test looks like this:

//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;
};

So far, my test code looks like this:

//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());
});

And I am currently getting an error: SQLite.openDatabase.mockReturnValue is not a function.

I am using expo 39.0.2 and expo-sqlite 8.4.0.

1 Answers

This does not directly answer your question, but is a workaround.

I have a repository.ts file containing SQLite functions

const db = SQLite.openDatabase('db.evready');

export const createDatabase = () => {
  db.transaction(...

Which I then mock in my tests like so:

jest.mock('../src/repository');

it('renders correctly', () => {
  renderer.create(<App />);

  jest.runOnlyPendingTimers();
});
Related