Marcos Chicote Marcos Chicote - 20 days ago 6
Node.js Question

Unit testing with Bookshelf.js and knex.js

I'm relatively new to Node and am working on a project using knex and bookshelf. I'm having a little bit of trouble unit testing my code and I'm not sure what I'm doing wrong.

Basically I have a model (called VorcuProduct) that looks like this:

var VorcuProduct = bs.Model.extend({
tableName: 'vorcu_products'
});

module.exports.VorcuProduct = VorcuProduct


And a function that saves a VorcuProduct if it does not exist on the DB. Quite simple. The function doing this looks like this:

function subscribeToUpdates(productInformation, callback) {
model.VorcuProduct
.where({product_id: productInformation.product_id, store_id: productInformation.store_id})
.fetch()
.then(function(existing_model) {
if (existing_model == undefined) {
new model.VorcuProduct(productInformation)
.save()
.then(function(new_model) { callback(null, new_model)})
.catch(callback);
} else {
callback(null, existing_model)
}
})
}


Which is the correct way to test this without hitting the DB? Do I need to mock
fetch
to return a model or undefined (depending on the test) and then do the same with
save
? Should I use rewire for this?

As you can see I'm a little bit lost, so any help will be appreciated.

Thanks!

Answer

I have been using in-memory Sqlite3 databases for automated testing with great success. My tests take 10 to 15 minutes to run against MySQL, but only 30 seconds or so with an in-memory sqlite3 database. Use :memory: for your connection string to utilize this technique.

A note about unit tesing - This is not true unit testing, since we're still running a query against a database. This is technically integration testing, however it runs within a reasonable time period and if you have a query-heavy application (like mine) then this technique is going to prove more effective at catching bugs than unit testing anyway.

Gotchas - Knex/Bookshelf initializes the connection at the start of the application, which means that you keep the context between tests. I would recommend writing a schema create/destroy script so that you and build and destroy the tables for each test. Also, Sqlite3 is less sensitive about foreign key constraints than MySQL or PostgreSQL, so make sure you run your app against one of those every now and then to ensure that your constraints will work properly.