jbrumwell / mock-knex

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

How to mock already initialized Bookshelf #4

Closed StephanHoyer closed 9 years ago

StephanHoyer commented 9 years ago

I want to use your lib to mock my bookshelf models.

I did the following.

var user = require('./user');
var knex = require('knex');
var mockDB = require('mock-knex');
var tracker = mockDB.getTracker();

describe('user model', function() {
  before(function() {
    mockDB.knex.use(knex);
    mockDB.knex.install();
    tracker.install();
  });
});

The models are still not mocked and fire normal queries. Seems like the creation of the bookshelft base model and of the models happens prior the mocking what causes it not to work properly.

What I'm doing wrong here?

jbrumwell commented 9 years ago

We need to mock knex prior to it be initiated. Not knowing your setup here is an example of what will and won't work

WIll Work;

mockDB.knex.install();

var db = knex({
  client : 'sqlite3'
});

Won't work;

var db = knex({
  client : 'sqlite3'
});

mockDB.knex.install();

Also the following only needs to be called once;

mockDB.knex.use(knex);
mockDB.knex.install();

Trackers can be installed and uninstalled on tests to avoid processing other tests responses.

StephanHoyer commented 9 years ago

I can't reach out to the initialisation of db, other tests that may run prior this test may invoke it.

Sorry, but I don't use mock-knex anymore. Tried it at least 4 times to get this running.

I now monkey-patch the prototype of my models which seem to work fine.