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`.
npm install knex-mock-clientVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to set up `knex-mock-client` with Jest, mock a Knex instance, configure query responses, and assert on executed queries.
Upgrade Node.js to version 18 or higher (LTS recommended) or pin `knex-mock-client` to a 2.x.x version in your `package.json`.
Replace direct calls to `MockClient.tracker` with `createTracker(db)` to get a tracker instance, as shown in the updated documentation and examples.
Install `knex` explicitly if it's not already a dependency: `npm install knex@latest` or `yarn add knex@latest`. Check your `package.json` for `knex` version compatibility.
Ensure your mocked Knex instance is initialized with `knex({ client: MockClient })` and that the module exporting your Knex instance is correctly mocked in your test file, e.g., `jest.mock('../common/db-setup', () => ({ db: knex({ client: MockClient }) }))`.Verify that your `knex` instance is initialized as `knex({ client: MockClient })` and that any module providing this instance is mocked correctly using your testing framework's facilities (e.g., `jest.mock`).Add a `tracker.on.<method>('<query matcher>').response(...)` handler for the specific query, ensuring the matcher (string, regex, or function) accurately covers the executed SQL.Ensure you are using `knex@>=2.0.0` and `knex-mock-client@>=2.0.1`. Also, ensure `knex` is imported from `knex` directly (e.g., `import { knex } from 'knex';`).