To follow on from the testing post I wrote on Findmypast tech blog for stubbing dependances in commonJS using proxyquire.

I thought it would be a worth sharing how I have gone about unit testing my code when using Reflux and SuperAgent libraries. The reason is to help get started and how to go about stubbing the superagent library. Hopefully this will help make that start a bit easier.

If the example below does not fully help with your scenario and you have questions please post questions in the comment box at the bottom. I will try to help by providing further examples.

Stubbing SuperAgent allows the application unit tests to be dependancy free from external APIs and prevents any unexpected issues from appearing.

The testing libraries used are mocha, shouldjs, sinon and should-sinon.

While this post is not about why I have chose these libraries I thought it would make a special mention for shouldJS and sinon-should. I’ve chosen to use shouldJS because they help with the readability of your test code one. ShouldJS is similar to the chaiJS and either one is a great choice.

The should-sinon helps make it easier to read asserts which check function calls are made and provide useful feedback if a test fails. For example:

// without should-sinon: gives a failed message of
// expected false to be true (confusing)
stubbedMethod.calledOnce.should.be.true();

// with should-sinon it will give a message expecting 'stubbedMethod' to be called once
stubbedMethod.should.be.calledOnce();

Stubbing SuperAgent with Sinon

Checkout the example gist of stubbing SuperAgent I’ve provided with comments. Below are more detailed explanations.

Importantly we setup a stub in the before function allowing calls on the put function to be watched and return our own fake response.

before(() => {
    putRequest = sinon.stub(superagent, 'put');
});

When the store function is called to make a request to the api and it is possible to return a custom response. Below is an example when SuperAgent put request is called, it will return a new object with an end function which update the callback params.

// At the start of the it function
putRequest.returns({
    end: (cb) => {
        cb(null, {ok: true, body: { "status" : "OK" }});
    }
});

To capture the params of the end callback, Sinon has a getCall function to return the params.

let response = myStore.trigger.getCall(0).args[0];

To update the state using Reflux the trigger callback should fire and using a spy the call can be captured.

successTrigger.should.be.calledOnce();

The putRequest can be checked if it has been called with the correct url and the expected response is returned.

putRequest.should.be.calledWith(URL);

response.status.should.eql('OK');

This is how I go about stubbing SuperAgent using Sinon. If you have any feedback or questions please post in the comments below.