Check Hapijs endpoint without getting into db

I am developing restApi using Hapi js. The structure of the project is as follows:

|-Root server.js |-router routes.js |-handlers authHandler.js |-db userDb.js 

The authentication request will go to route.js and redirected to authHandler.js, which in turn calls userDb.js. userDb.js talks to the database and returns the result of authHandler.js that return a response to the client.

I am trying to write a test where userDb.js is not talking to the database

For this, I use Hapi inject to be able to call routes without actually starting the server. I'm struggling to figure out how to mock a database in a call chain so that I can provide a dummy answer.

In short, I want userDb.js to be replaced with a layout when testing.

+6
source share
1 answer

After the suggestion from @AlbertZaccagni above, I consulted the documentation from Sinon, and I came up with the following:

NB: I omit code that declares routes and other integral parts of the question.

Assuming userDb.js is a module that connects to the database, and that I want to mock the answer from the database:

userDb.js is as follows:

 var db = require(/*path to db */); module.exports.getUser = function(id, callback){ db.query('sql query', function(err, rows){ if(err){ return callback(err); } return callback(null, rows[0]);/*returns the first object- in the resultset from the database.*/ }); } 

In my test folder, I created the mytest.js file with the following contents:

 //don't forget to install sinon JS via npm var sinon = require('sinon'); var server = require(/*path to hapi server*/); var userDb = require(/*path to the module we are stubbing/mocking*/); describe('Stub test', function(){ var options = {}; options.method = 'GET'; options.url = '/user/1'; it('with stubbing', function(done) { var stub = sinon.stub(userDb, 'getUser', function(id, callback) { if (id < 5) { return callback(null, 100);/*in this case i'm just testing to see if this function will get called instead- of the actual function. That why 100.*/ } return new Error('test error'); }); server.inject(options, function(res) { var result = res.result; res.statusCode.should.equal(200); result.num.should.equal(100); done(); }); }); }); 

When I run the npm test in my working directory, I see that it passes without actually calling the database and returns 100 for username 1.

+2
source

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


All Articles