jbrumwell / mock-knex

A mock knex adapter for simulating a database during testing
MIT License
239 stars 71 forks source link

Reject doesn't create an error #93

Closed Jerome1337 closed 4 years ago

Jerome1337 commented 4 years ago

This following code doesn't throw any error, I still get the same response I get when I put a query.response({})

it('should throw a bad request error', () => {
  knexTracker.on('query', (query) => {
    console.log(query);
    query.reject(Error('My error'));
  });

  return getUser({ params: { username: 'randomUser' } }).catch((error) => {
    console.log(error);
  });
});

For your information the getUser method is the following:

function getUser(request) {
  const { username } = request.params;

  return Knex('users')
    .first()
    .where('username', username)
    .then((user) => user)
    // the test should pass here
    .catch(() => Boom.badRequest(`Error while finding user "${username}"`));
}

The first console log return a classic query object

{
  method: 'first',
  sql: 'select * from `users` where `username` = ? limit ?',
  bindings: [ 'randomUser', 1 ],
  transacting: false,
  response: [Function: response],
  resolve: [Function: resolve],
  reject: [Function: reject],
  step: 1
}

Did I miss something or this is a real problem?

jbrumwell commented 4 years ago

We previously had a test for rejecting on a string but not an error, I have added a test here that passes through the supported version;

https://github.com/colonyamerican/mock-knex/pull/94/files

That said I think what may be happening here is that in your getUser method you expect

.catch(() => Boom.badRequest(`Error while finding user "${username}"`));

to rethrow an error when in fact it will return an error. If you change this to;

.catch(() => throw Boom.badRequest(`Error while finding user "${username}"`));

I think your test will pass