简体   繁体   中英

Sinon Spy and Stub function through actual http request

I have a function which is called from an API. I can stub it using sinon if I directly call it in my test for example foo.bar(); But if I call it through a test that makes an http request to that function it doesn't get stubbed. Any ideas?

You need to be able to start your application from the tests, and you should structure you application in a way that you can inject the dependencies that you want to control.

In the code below I have tried showing how you can use link seams (using proxyquire) to control the dependencies, but you could also use direct dependency injection to your app (say, pass it in to the start() method) as an alternative.

The code below is instructive, not necessarily working, so it skips setting up http listeners properly, etc. That is left as an exercise for the reader ;)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM