我正在尝试编写UnitTests测试,我的想法是保留外部API调用。
// handler.js
const Service = require('./lib/api/service');
const Worker = require('./lib/api/worker');
module.exports.handlerFunction = (event, context, callback) => {
# do some thing here
if(some_condition) {
const worker = new Worker();
worker.invoke(event.event_a, event.event_b, null, callback);
} else {
const service = new Service();
service.invoke(event.event_a, event.event_b, null, callback);
}
}
茉莉花规格
// specs
it('checks if Service gets invoked.', () => {
const stub = sinon.stub(Service.prototype, 'invoke').returns(new Promise((resolve) => {
resolve('success');
}));
let handler = proxyquire('../../handler', { 'Service': stub });
handler.handlerFunction({ event_a: 1000, event_b: '1000' }, { some_context: 'context' }, (error, returnValue) => {
expect(stub.called).toEqual(true);
});
stub.restore();
});
但是上面的代码不起作用。当在实例化对象的上下文中使用proxyquire
时,该代码有效。如果无法通过proxyquire
非常感谢。