我有一个从 API 调用的函数。如果我在测试中直接调用它,我可以使用 sinon 对其进行 stub ,例如 foo.bar();但是,如果我通过向该函数发出 http 请求的测试来调用它,它就不会被 stub 。有什么想法吗?
最佳答案
您需要能够从测试启动应用程序,并且应该以可以注入(inject)要控制的依赖项的方式构建应用程序。
在下面的代码中,我尝试展示如何使用链接接缝(使用 proxyquire)来控制依赖项,但您也可以使用直接依赖项注入(inject)到您的应用程序(例如,将其传递到 start( )
方法)作为替代方案。
下面的代码具有指导意义,但不一定有效,因此它会跳过正确设置 http 监听器等。这留给读者作为练习;)
app.js
const myModule = require('./my-module');
if (require.main === module) {
/// starting from the cli
start({});
}
module.exports = {
start(){
app.get(`/`, (req, res) => {
myModule.foo(req.data).then(res.send).catch(res.send);
});
});
stop(){
app.stop(); // somehow kill the http listener and shutdown
}
}
测试.js
const stub = sinon.stub();
const myApp = proxyquire('../app.js',{'./my-module': {foo: stub } });
before(()=> {
myApp.start();
});
it('should call a sinon stub', (done) => {
request('localhost:3000/')
.then( result = > expect(stub.called).to.equal(true) )
.then(done, done);
});
关于javascript - 通过实际http请求的Sinon Spy和Stub功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49783797/