Knex Mock Client

3.0.2 · active · verified Tue Apr 21

knex-mock-client is a testing utility designed to provide a comprehensive mock client for Knex.js, enabling developers to write isolated unit tests for database interactions without needing an actual database connection. The current stable version is 3.0.2. The library maintains an active release cadence, frequently publishing patch and minor versions to address bug fixes, improve type safety, and add new features like support for transaction isolation levels. Its key differentiators include flexible query matching (string, regex, or custom function), explicit control over response data and errors for different query types (select, insert, update, delete, any), and the ability to track executed queries for assertions. It's built to integrate seamlessly into testing frameworks like Jest by allowing the Knex client to be mocked with `MockClient`.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up `knex-mock-client` with Jest, mock a Knex instance, configure query responses, and assert on executed queries.

import { createTracker, MockClient } from 'knex-mock-client';
import { knex } from 'knex'; // Peer dependency

// Imagine this is your actual DB setup file that gets mocked
const db = knex({ client: MockClient });

// A function that uses the knex instance
async function getUsersOlderThan(age: number) {
  return db('users').where('age', '>', age).select();
}

describe('User Service', () => {
  let tracker: ReturnType<typeof createTracker>;

  beforeEach(() => {
    tracker = createTracker(db); // Initialize a new tracker before each test
  });

  afterEach(() => {
    tracker.reset(); // Clear all mock handlers and query history after each test
  });

  it('should retrieve users older than a given age', async () => {
    const mockUsers = [
      { id: 1, name: 'Alice', age: 30 },
      { id: 2, name: 'Bob', age: 35 }
    ];

    // Configure the tracker to respond to a specific query
    tracker.on.select('users').response(mockUsers);

    const users = await getUsersOlderThan(25);

    expect(users).toEqual(mockUsers);

    // Verify the query that was executed
    const selectHistory = tracker.history.select;
    expect(selectHistory).toHaveLength(1);
    expect(selectHistory[0].method).toEqual('select');
    expect(selectHistory[0].sql).toContain('select * from `users` where `age` > ?');
    expect(selectHistory[0].bindings).toEqual([25]);
  });

  it('should handle no users found', async () => {
    tracker.on.select('users').responseOnce([]);

    const users = await getUsersOlderThan(40);

    expect(users).toEqual([]);
    expect(tracker.history.select).toHaveLength(1);
  });
});

view raw JSON →