{"id":15669,"library":"knex-mock-client","title":"Knex Mock Client","description":"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`.","status":"active","version":"3.0.2","language":"javascript","source_language":"en","source_url":"https://github.com/felixmosh/knex-mock-client","tags":["javascript","typescript"],"install":[{"cmd":"npm install knex-mock-client","lang":"bash","label":"npm"},{"cmd":"yarn add knex-mock-client","lang":"bash","label":"yarn"},{"cmd":"pnpm add knex-mock-client","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Peer dependency, required at runtime for type compatibility and to be used as the underlying client for the mock.","package":"knex","optional":false}],"imports":[{"note":"ESM is the preferred import style; CJS works but types are better with ESM. `createTracker` is a factory function to initialize a new tracker instance.","wrong":"const { createTracker } = require('knex-mock-client');","symbol":"createTracker","correct":"import { createTracker } from 'knex-mock-client';"},{"note":"This is a named export. `MockClient` is the class used to configure Knex for mocking, typically passed to `knex({ client: MockClient })`.","wrong":"import MockClient from 'knex-mock-client';","symbol":"MockClient","correct":"import { MockClient } from 'knex-mock-client';"},{"note":"This is a named type export, crucial for TypeScript users to correctly type the tracker instance returned by `createTracker`.","wrong":"import type { Tracker } from 'knex-mock-client/tracker';","symbol":"Tracker","correct":"import { Tracker } from 'knex-mock-client';"}],"quickstart":{"code":"import { createTracker, MockClient } from 'knex-mock-client';\nimport { knex } from 'knex'; // Peer dependency\n\n// Imagine this is your actual DB setup file that gets mocked\nconst db = knex({ client: MockClient });\n\n// A function that uses the knex instance\nasync function getUsersOlderThan(age: number) {\n  return db('users').where('age', '>', age).select();\n}\n\ndescribe('User Service', () => {\n  let tracker: ReturnType<typeof createTracker>;\n\n  beforeEach(() => {\n    tracker = createTracker(db); // Initialize a new tracker before each test\n  });\n\n  afterEach(() => {\n    tracker.reset(); // Clear all mock handlers and query history after each test\n  });\n\n  it('should retrieve users older than a given age', async () => {\n    const mockUsers = [\n      { id: 1, name: 'Alice', age: 30 },\n      { id: 2, name: 'Bob', age: 35 }\n    ];\n\n    // Configure the tracker to respond to a specific query\n    tracker.on.select('users').response(mockUsers);\n\n    const users = await getUsersOlderThan(25);\n\n    expect(users).toEqual(mockUsers);\n\n    // Verify the query that was executed\n    const selectHistory = tracker.history.select;\n    expect(selectHistory).toHaveLength(1);\n    expect(selectHistory[0].method).toEqual('select');\n    expect(selectHistory[0].sql).toContain('select * from `users` where `age` > ?');\n    expect(selectHistory[0].bindings).toEqual([25]);\n  });\n\n  it('should handle no users found', async () => {\n    tracker.on.select('users').responseOnce([]);\n\n    const users = await getUsersOlderThan(40);\n\n    expect(users).toEqual([]);\n    expect(tracker.history.select).toHaveLength(1);\n  });\n});","lang":"typescript","description":"This quickstart demonstrates how to set up `knex-mock-client` with Jest, mock a Knex instance, configure query responses, and assert on executed queries."},"warnings":[{"fix":"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`.","message":"Version 3.0.0 of `knex-mock-client` dropped support for Node.js versions older than 18. Users on Node.js 16 or earlier must upgrade their Node.js environment or remain on `knex-mock-client` v2.x.x.","severity":"breaking","affected_versions":">=3.0.0"},{"fix":"Replace direct calls to `MockClient.tracker` with `createTracker(db)` to get a tracker instance, as shown in the updated documentation and examples.","message":"In version 2.0.0, the `MockClient.tracker` property was changed from static to an instance property. This means you can no longer access `MockClient.tracker` directly, but instead need to obtain the tracker instance via `createTracker(db)` where `db` is your Knex instance configured with `MockClient`.","severity":"breaking","affected_versions":">=2.0.0"},{"fix":"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.","message":"`knex-mock-client` relies on `knex` as a peer dependency, specifically requiring `knex@>=2.0.0`. Ensure you have a compatible version of `knex` installed in your project, otherwise, you may encounter type mismatches or runtime errors.","severity":"gotcha","affected_versions":">=2.0.1"},{"fix":"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 }) }))`.","message":"When mocking the Knex client, especially with module mocking utilities like `jest.mock`, it's crucial to correctly configure the Knex instance to use `MockClient`. Incorrect setup can lead to the mock not being applied, resulting in real database calls or errors like 'Client not supported'.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-21T00:00:00.000Z","next_check":"2026-07-20T00:00:00.000Z","problems":[{"fix":"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`).","cause":"The Knex instance being used in the test is not correctly configured with `MockClient`, or the module exporting the Knex instance was not properly mocked.","error":"TypeError: Cannot read properties of undefined (reading 'insert')"},{"fix":"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.","cause":"The `knex-mock-client` tracker received a query that does not match any of the configured `on.response` or `on.responseOnce` handlers.","error":"Query not handled by tracker: { method: 'select', sql: '...', bindings: [...] }"},{"fix":"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';`).","cause":"This usually indicates a mismatch in TypeScript versions, `knex` versions, or an incorrect `knex` import that leads to type incompatibility for the `client` property.","error":"Type 'typeof MockClient' is not assignable to type 'ClientConstructor<any>'"}],"ecosystem":"npm"}