user1381745
user1381745

Reputation: 3900

Sinon stub.resolves() not acting as desired

Here's the function I'm writing tests for:

ensureUserDoesNotExist(request, response, next) {
  this.User.findOne({ where: { email: request.body.email }})
    .then(user => {
      if (user) {
        response.sendStatus(403);
      } else {
        next();
      }
    });
  }

And here's the test that I cannot get to pass:

it('should return a 403 if a matching user is found', () => {
  mockRequest.body.email = '[email protected]';
  userController.User.findOne.resolves(true); // This is a previously created sinon stub
  userController.ensureUserDoesNotExist(mockRequest, mockResponse, mockNext);
  assert(mockResponse.sendStatus.calledWith(403));
});

It fails, simply claiming that the stub isn't called (at all, for what it's worth).

I strongly suspect this is to do with the promise - or Sinon's interaction with it - but am having a complete mind-blank in trying to figure out exactly what. The code works as intended (or it did when I last looked before playing about with it). Can anyone help me out?

Upvotes: 0

Views: 1768

Answers (2)

sripberger
sripberger

Reputation: 1732

The test also must return a promise to indicate an asynchronous test to Mocha. You can use the one returned by the then call:

it('should return a 403 if a matching user is found', () => {
  mockRequest.body.email = '[email protected]';
  userController.User.findOne.resolves(true); // This is a previously created sinon stub
  return userController.ensureUserDoesNotExist(mockRequest, mockResponse, mockNext).then(() => {
      assert(mockResponse.sendStatus.calledWith(403));
  });
});

Upvotes: 0

Troopers
Troopers

Reputation: 5452

Your assertion is evaluated before the end request You need to return the promise

ensureUserDoesNotExist(request, response, next) {
  return this.User.findOne({ where: { email: request.body.email }})
    .then(user => {
      if (user) {
        response.sendStatus(403);
      } else {
        next();
      }
    });
  }

and assert in then clause

it('should return a 403 if a matching user is found', () => {
  mockRequest.body.email = '[email protected]';
  userController.User.findOne.resolves(true); // This is a previously created sinon stub
  userController.ensureUserDoesNotExist(mockRequest, mockResponse, mockNext).then(() => {
     assert(mockResponse.sendStatus.calledWith(403));
  });
});

Upvotes: 2

Related Questions