0

我正在使用自定义插件在一些 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注入假数据库插件?

4

1 回答 1

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 的清单,但这是我目前能做的最好的事情。

于 2017-11-30T23:50:13.250 回答