Sinon Spy和Stub功能通过实际的http请求

时间:2018-04-11 20:15:57

标签: javascript node.js mocha sinon

我有一个从API调用的函数。如果我在我的测试中直接调用它,例如foo.bar();我可以使用sinon将其存根。但是,如果我通过一个对该函数发出http请求的测试来调用它,它就不会被删除。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

您需要能够从测试中启动应用程序,并且应该以可以注入要控制的依赖项的方式构建应用程序。

在下面的代码中,我尝试了如何使用链接接口(使用proxyquire)来控制依赖关系,但您也可以使用直接依赖注入到您的应用程序(例如,将其传递给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 
    }
}

test.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);  
});