Rapid testing of JS integration with Supertest and mock database

Is it possible to test the Express JS REST API using a super test, but replacing the actual database connection with the mock database object? I have unit tests covering database models and other parts of the application, as well as API endpoint functional tests that make actual database connections, but I have a weird requirement for creating integration tests that are similar to functional tests but use connections to databases. The following is an example of an endpoint controller:

var model = require('../../../lib/models/list'); module.exports = { index: function(req, res) { var data = { key: 'domains', table: 'demo.events'}; var dataModel = new model(data); dataModel.query().then(function(results) { res.respond({data: results}, 200); }).fail(function(err) { console.log(err); res.respond({message: 'there was an error retrieving data'}, 500); }); } }; 

And the index for the URI

 var express = require('express'), app, exports; app = exports = module.exports = express(); exports.callbacks = require('./controller'); app.get('/', exports.callbacks.index); 

The list model used in the controller connects to the database and retrieves the data that is output. The problem is bullying that the actual database call is still using supertest to query and retrieve data from the URI

Any information would be helpful, including if you think this is a bad or pointless idea.

+6
source share
1 answer

I have had limited success with two approaches:

1) use rewire to replace the database driver library, such as mongodb, with a mockery, possibly using the spy / stub / mock sinon features

2) Set db as the application parameter via app.set('mongodb', connectedDb) for dev / prod, but in the test environment, install the mock database instead. This requires your access code (for example, models) in order to get the database from the application or otherwise be layout friendly or designed with a dependency injection template.

None of them makes everything clean and painless, but I got some usefulness from them.

+6
source

Source: https://habr.com/ru/post/956203/


All Articles