felixmosh / knex-mock-client

A mock client for knex which allows you to write unit tests with DB interactions

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Mock handler not found error when using jest async assertion helpers

misskaseyann opened this issue · comments

Issue

When testing asynchronous functions, Jest has some handy helpers to reduce the boiler plate of try {} ... catch() {}

It appears that when using knex-mock-client, if the function being tested is async and any of these helpers are being used (i.e. expect(foo()).rejects.throwError(/wow big error/i);, I will get an error that appears to be coming from knex-mock-client that looks somewhat like: "select \"id\" from \"foo\" where \"name\" = 'bar' limit 1 - Mock handler not found"

Expected behavior

I would expect that the behavior of knex-mock-client would be the same regardless if I used try {} ... catch() {} or expect(foo()).rejects...

Code snippet

Here is a quick code snippet (not full implementation) that shows this error happening:

import { createTracker, MockClient, Tracker } from 'knex-mock-client';
import knex from 'knex';
import { db } from '../datasources/connections/db';
import { subject } from '../service';

jest.mock('../datasources/connections/db', () => {
  return {
    db: knex({ client: MockClient }),
  };
});

describe('example', () => {
  let tracker: Tracker;

  beforeAll(() => {
    tracker = createTracker(db);
  });

  afterEach(() => {
    tracker.reset();
  });

  it('fails', async () => {
    tracker.on.select('foo').response([{ id: 'bar' }]);

    // 🚨 Fails with error "select \"id\" from \"foo\" - Mock handler not found"
    expect(subject()).rejects.toThrowError(
      /not all foos were found/i
    );
  });

  it('works', async () => {
    tracker.on.select('foo').response([{ id: 'bar' }]);

    // 🚨 Works
    try {
      await subject();
    } catch (err) {
      expect(err.message).toMatch(/not all foos were found/i);
    }
  });
});

Versions

"mock-knex": "^0.4.13"
"jest": "29.4.3"
"knex": "2.4.2"

Thank you for reporting this issue, but It probably not related to this lib, in order to use rejects you need to pass the expect a function that returns a promise, in your case, you give it a promise.

Try,

it('fails', async () => {
    tracker.on.select('foo').response([{ id: 'bar' }]);

    // 🚨 Fails with error "select \"id\" from \"foo\" - Mock handler not found"
    expect(() => subject()).rejects.toThrowError(
      /not all foos were found/i
    );
  });

Thank you for the quick reply @felixmosh ❤️

I just realized this! Thanks for being my rubber ducky!