Skip to content Skip to sidebar Skip to footer

Sinon - Stubbing Function With Callback - Causing Test Method To Timeout

I have a method on a express route that looks like this: exports.register_post = function(req, res) { var account = new Account(); account.firstName = req.param('firstName'

Solution 1:

Sinon stubs will not automatically fire any callback functions, you need to do this manually. It's actually really east to do though:

describe('POST /account/register', function(done) {

    var email;

    beforeEach(function(done) {
        accountToPost = {
            firstName: 'Alex',
        };

        email = require('../../app/helpers/email');
        sinon.stub(email);
        email.sendOne.callsArg(2);

        done();
    });

    afterEach(function(done) {
        email.sendOne.restore();
        done();
    })

    it('creates account', function(done) {
        request(app)
            .post('/account/register')
            .send(this.accountToPost)
            .expect(200)
            .end(function(err, res) {
                should.not.exist(err)
                //todo: assertsdone();
            });
    });

    it('sends welcome email', function(done) {
        request(app)
            .post('/account/register')
            .send(this.accountToPost)
            .expect(200)
            .end(function(err, res) {
                should.not.exist(err)
                sinon.assert.calledWith(email.sendOne, 'welcome');
                done();
            });
    });
});

Notice the specific line:

        email.sendOne.callsArg(2);

The Sinon Stubs API has some good documentation on callsArg, and also callsArgWith (which may be useful for you testing error scenarios)

Post a Comment for "Sinon - Stubbing Function With Callback - Causing Test Method To Timeout"