jbrumwell / mock-knex

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

mock-knex breaks main connexion when used on other connexion #125

Open mlarcher opened 3 years ago

mlarcher commented 3 years ago

We have a codebase that needs to connect to a secondary database for sync purpose. Adding mockKnex.mock(connection); to this secondary database connection breaks the main database connection. This is unexpected, as we pass the actual specific connection to mockKnex.mock(). Is there a workaround to that behavior ?

Here's an example of what that looks like :

// db.js
const knex = require('knex');

const knexfile = require('../../knexfile');
const config = require('./config');

const connection = knex({
  ...knexfile.production,
  debug: config.get('db:debug'),
});

module.exports = connection;
// secondaryDb.js
const knex = require('knex');
const mockKnex = require('mock-knex');

const config = require('./config');

const connection = knex({
  client: config.get('secondaryDb:client'),
  debug: config.get('secondaryDb:debug'),
  connection: {
    host: config.get('secondaryDb:connection:host'),
    database: config.get('secondaryDb:connection:database'),
    user: config.get('secondaryDb:connection:user'),
    password: config.get('secondaryDb:connection:password'),
    port: config.get('secondaryDb:connection:port'),
  },
});

// this line breaks calls made to db.js instance
mockKnex.mock(connection);

module.exports = connection;
const db = require('./db.js');
const secondaryDb = require('./secondaryDb.js');

const result = await db.from('someTable').select('*');

// when `mockKnex.mock(connection);` is active on secondaryDb, `result` from the main db is undefined
console.log(result);
danmichaelo commented 1 year ago

Seems like this is because a single, shared instance of MockKnex is exported: https://github.com/jbrumwell/mock-knex/blob/master/src/index.js#L103 ?

Would be awesome if the MockKnex class was exported as well, so we could create multiple MockKnex instances.