如何使用Server.inject注入模拟测试hapi

时间:2023-01-21 12:08:13

I want to test hapi routes with lab, I am using mysql database.

我想用实验室测试hapi路由,我正在使用mysql数据库。

The problem using Server.inject to test the route is that i can't mock the database because I am not calling the file that contains the handler function, so how do I inject mock database in handler?

使用Server.inject来测试路由的问题是我无法模拟数据库因为我没有调用包含处理函数的文件,所以如何在处理程序中注入模拟数据库?

1 个解决方案

#1


5  

You should be able to use something like sinon to mock anything you require. For example, let's say you have a dbHandler.js somewhere:

你应该能够使用像sinon这样的东西来模拟你需要的东西。例如,假设你有一个dbHandler.js:

var db = require('db');

module.exports.handleOne = function(request, reply) {
    reply(db.findOne());
}

And then in your server.js:

然后在你的server.js中:

var Hapi = require('hapi'),
    dbHandler = require('dbHandler')

var server = new Hapi.Server(); server.connection({ port: 3000 });

server.route({
    method: 'GET',
    path: '/',
    handler: dbHandler.handleOne
});

You can still mock out that call, because all calls to require are cached. So, in your test.js:

您仍然可以模拟该调用,因为所有对require的调用都会被缓存。所以,在你的test.js中:

var sinon = require('sinon'),
    server = require('server'),
    db = require('db');

sinon.stub(db, 'findOne').returns({ one: 'fakeOne' });
// now the real findOne won't be called until you call db.findOne.restore()
server.inject({ url: '/' }, function (res) {
    expect(res.one).to.equal('fakeOne');
});

#1


5  

You should be able to use something like sinon to mock anything you require. For example, let's say you have a dbHandler.js somewhere:

你应该能够使用像sinon这样的东西来模拟你需要的东西。例如,假设你有一个dbHandler.js:

var db = require('db');

module.exports.handleOne = function(request, reply) {
    reply(db.findOne());
}

And then in your server.js:

然后在你的server.js中:

var Hapi = require('hapi'),
    dbHandler = require('dbHandler')

var server = new Hapi.Server(); server.connection({ port: 3000 });

server.route({
    method: 'GET',
    path: '/',
    handler: dbHandler.handleOne
});

You can still mock out that call, because all calls to require are cached. So, in your test.js:

您仍然可以模拟该调用,因为所有对require的调用都会被缓存。所以,在你的test.js中:

var sinon = require('sinon'),
    server = require('server'),
    db = require('db');

sinon.stub(db, 'findOne').returns({ one: 'fakeOne' });
// now the real findOne won't be called until you call db.findOne.restore()
server.inject({ url: '/' }, function (res) {
    expect(res.one).to.equal('fakeOne');
});