jbrumwell / mock-knex

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

TypeError thrown after mocked database save #66

Closed nmagerko closed 7 years ago

nmagerko commented 7 years ago

I'm using mock-knex to mock a knex instance as follows:

var mockknex = require('mock-knex');
var knex = require('knex');
var bookshelf = require('bookshelf');

var knexInstance = knex([...]);
mockknex.mock(knex);

var bookshelfInstance = bookshelf(knex);

The mocked knex instance is then passed to bookshelf so that I can run some tests. However, I eventually get the following error at the end of my tests:

TypeError: Cannot read property '0' of undefined
    at null.<anonymous> (/.../node_modules/bookshelf/lib/model.js:1015:57)

For reference, that line in the bookshelf library can be found here. This does not happen when I do not mock the knex instance, so I wonder if it could be because I'm using this library incorrectly or if there might be a bug.

nmagerko commented 7 years ago

Additionally, it seems like this is the line that's causing the error. Note MyModel here is the result of extending bookshelf's base Model:

MyModel.forge({ ... }).save()

I believe I'm using this pattern of forging and saving elsewhere with the mocked knex instance, so I'm not sure what could cause that error in this case alone.

jbrumwell commented 7 years ago

@nmagerko it looks like your tracker is not returning a response for the save query so it is getting an undefined response on the save method. Take a look here https://github.com/colonyamerican/mock-knex/blob/5c3e385cd7d4e85e5b90f32ed1bcac03d8de276e/test/common/bookshelf.js#L199

Instead of the assertions of the test you would call query.response([ {..} ]); and it would then process like a regular insert / update

nmagerko commented 7 years ago

@jbrumwell That was it – didn't quite understand what the tracker was for in that situation, but now I see why it's there. Any reason why query.response([]); isn't the default behavior? That seems to make it work for me.

Is the reason because people might see unexpected behavior if the tracker was returning empty results on queries? If so, that makes sense (just trying to understand how things work).

Anyhow, this fixed it. Thanks!