How can I mock a fake database for unit testing against Knex?

I have successfully used Knex to connect to the database. But I want to be able to unit test my code. Is there a way to trick a database connection?

I tried using proxyquire , but I can't get it to work.

The problem seems to be related to Knex initialization.

var knex = require('knex')({ client: 'mysql', connection: {} }); 

I install knex to taunt in my unit test.

 myService = proxyquire('../app/myService', { 'knex': knexProxy }); 

There is knex in my service.

 var knex = require('knex').knex, 

When my service starts a request, it fails.

 var sql = knex("table_name"); sql.insert(rowToInsert, "auto_increment_id"); sql.then(function (insertId) { resolve(); }, function (err) { reject(err); }); 

For some reason, I just can't capture the request before it tries to establish a connection.

I also tried creating a custom Knex Client , but that still didn't work.

+8
javascript unit-testing proxyquire
source share
3 answers

I use Sqlite3 databases in memory for automatic testing with great success. This is not true unit testing, but it works much faster than MySQL or PostgreSQL. I added additional information about this decision on another issue .

+1
source share

I used jest to mock knex, but I had to define an object containing the method that I used. not the most elegant solution, but it works

 let knexMock = () => { const fn = () => { return { returning: function() { return { insert: jest.fn().mockImplementation(() => [123123]) } }, insert: jest.fn() } } fn.raw = jest.fn() return fn } knex.mockImplementation(knexMock) 
0
source share

Using a joke :

Create the file /__mocks__/knex.js in the root of your application:

 module.exports = () => ({ select: jest.fn().mockReturnThis(), from: jest.fn().mockReturnThis(), where: jest.fn().mockReturnThis(), first: jest.fn().mockReturnThis(), then: jest.fn(function (done) { done(null) }) }) 

Pass the desired return value done

0
source share

All Articles