Building SQL QueriesDocumentation

SQLite Testing

The @databases/sqlite module defaults to an in-memory database in node.js, meaning you can get an isolated database for every test run.


Assuming you have a file that looks like:

// db.js
import connect, {sql} from '@databases/sqlite';

export {sql};

const db = connect('./data');
export default db;

You can add a mock:

// db.mock.js
import connect, {sql} from '@databases/sqlite';

export {sql};

const db = connect(); // in memory db
export default db;

Then in you test, you can tell jest to use your mock:

jest.setMock('../db', require('../db.mock'));
import db, {sql} from '../db';

test('createUser', async () => {
  await createUser('Joe Blogs', '');
  expect(await db.query(sql`SELECT name, email FROM users`)).toEqual([
    {name: 'Joe Blogs', email: ''},

The nice thing about this is every test gets its own isolated copy of the database.

Synchronous API