Sinon spy with a promise that is not called

The test (below) for this piece of code doesn't work:

module.exports = function(User, jwt) {
  'use strict';

  return function(req, res) {
    User.create(req.body)
    .then(function(id) {
      var token = jwt.sign({id: id}); 
      res.json({token: token});
    });
  };
};

      

Here's a test:

'use strict';
var chai = require('chai');
var sinon = require('sinon');
require('sinon-as-promised');

chai.should();
chai.use(require('sinon-chai'));

describe('routes/signup', function() {

  var User;
  var request;
  var response;
  var jwt;
  var signup;

  beforeEach(function() {
    User = {create: sinon.stub()};
    request = {body: 'body'};
    response = {json: sinon.spy()};
    jwt = {sign: sinon.stub().withArgs({id:'id'}).returns('token')};
    signup = require('../../../routes/signup')(User, jwt);
  });

  it('returns token when resolving', function() {
    User.create.resolves('id');
    signup(request, response);
    return response.json.should.have.been.calledWith({token: 'token'});
  });
});

      

If I poll the response.json method it never seems to have been called. response.args is an empty array.

I'm guessing I'm missing something fundamental with promises testing. Help!

+3


source to share


1 answer


Remember that promises are asynchronous, so you need to wait until the promise is resolved and then call a method then

to fulfill your assertions. Fr0609's response will give you a false positive because it will return before the block is called then

.

Try the following:



it('returns token when resolving', function(done) {

  User.create.resolves('id');

  signup(request, response)
    .then(function() {
      response.json.should.have.been.calledWith({token: 'token'});
      done();
    })
    .catch(done);
});

      

+2


source







All Articles