我正在使用自定义插件在一些 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.db
和request.server.app.db
完全是两个不同的对象。我也尝试了猴子补丁server.root.app.db
,但无济于事。
有没有办法存根db
对象,或者我需要用来proxyquire
注入假数据库插件?