无法从自定义插件中存储共享对象以进行单元测试

时间:2017-11-29 00:06:01

标签: hapijs lab

我正在使用自定义插件在一些hapi模块之间共享一些持久性方法:

const Mongoose = require('mongoose');
const Promise = require('bluebird');    
const Models = require('./persistence/mongodb/models');
exports.register = (server, options, next) => {
    Mongoose.Promise = Promise;
    Mongoose.set('debug', 'true');
    const mongoConnectionUri = process.env.MONGO_URI || 
           'mongodb://localhost/foo';
    Mongoose.connect(mongoConnectionUri, { useMongoClient: true })
    .then(() => {
        // eslint-disable-next-line no-param-reassign
        server.app.db = Models;
    });

next();
};

可以这样访问,并且工作正常:

module.exports.doSomething = async (request, reply) => {
    const Models = request.server.app.db;
    const data = await Models.persistenceMethod();
    reply(data);
}

然而,我正在努力模仿persistenceMethod()。我试过Sinon或猴子修补:

test('retrieves data', async () => {
    server.app.db = {
        persistenceMethod: () =>
            // eslint-disable-next-line no-unused-vars
            new Promise((resolve, reject) => resolve({ foo: 'bar' }))
    };

    const expectedPayload = [ { foo: 'bar' } ];
    const response = await server.inject({'GET', '/api/getFoo'});
    const payload = response.payload;
    expect(response.statusCode).to.equal(200);
    expect(JSON.parse(payload)).to.deep.equal(expectedPayload);
});    

但似乎server.app.dbrequest.server.app.db完全是两个不同的对象。我也尝试了猴子修补server.root.app.db,但无济于事。

有没有办法存根db对象,还是需要使用proxyquire注入假数据库插件?

1 个答案:

答案 0 :(得分:0)

我仍然没有找到解决原始问题的方法,而是使用Glue注入模拟数据库插件:

exports.register = (server, options, next) => {
// eslint-disable-next-line no-param-reassign
server.app.db = {
    persistenceMethod: () => new Promise((resolve, reject) => {
        resolve({foo: 'bar'});
    })};
    next();
};

我不想触及Glue的清单,但它是我现在能做的最好的。