Jasmine: the test that returned the promise is a specific exception

I have a method on my node.js server that returns Promise - throws a custom exception ( UserNotAuthenticatedError) - and I want to write a test to make sure that this Exception is thrown whenever necessary.

The method is as follows:

export function changePassword(userId, oldPass, newPass) {
  var query = User.findById(userId);
  return query.exec()
    .then(user => {
      if (user.authenticate(oldPass)) {
        user.password = newPass;
        return user.save();
      } else {
        // I want to test that this Exception is thrown
        throw new UserNotAuthenticatedError();
      }
    });
}

I tried to write a test, and this is what I still have:

describe('#changePassword', function() {
    it('should throw a UserNotAuthenticatedError when passing wrong password', function() {
      var userId = user._id;
      var wrongPwd = 'wrongpassword';
      var newPwd = 'new password';
      // so far the following only tells me that the Promise was rejected, but
      // I WANT TO TEST THAT THE REJECTION WAS DUE TO A 'UserNotAuthenticatedError'
      UserService.changePassword(userId, wrongPwd, newPwd).should.be.rejected;
    });
  });

I performed a check that the promise was returned was rejected, but I also want to be more specific and check that the returned promise is this UserNotAuthenticatedError. How can i do this?

+4
source share
3

- :

it('should throw a UserNotAuthenticatedError when passing wrong password', function() {
  var userId = user._id;
  var wrongPwd = 'wrongpassword';
  var newPwd = 'new password';

  var promise = UserService.changePassword(userId, wrongPwd, newPwd);
  return promise.should.be.rejectedWith(UserNotAuthenticatedError);
});
+3

promise.catch(function(error){}) error, , ?

+1

I guess there are better ways to handle this than the one I suggest. That should work though.

var promise = UserService.changePassword(userId, wrongPwd, newPwd);
var error = null;
promise.should.be.rejected;
promise.then(function(){}, function(err){
    expect(err).toEqual(jasmine.any(UserNotAuthenticatedError));
    done();
});

If done, this is a function that can be passed as a parameter to its method. He points out that this is an asynchronous test.

+1
source

All Articles