无法从单元测试的自定义插件存根共享对象

Cannot stub shared object from custom plugin for unit tests

我正在使用自定义插件在一些 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 或 monkey-patching:

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 来注入假数据库插件?

我仍然没有找到解决原始问题的方法,而是使用 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 的清单,但这是我目前能做的最好的事情了。