2

I have a very simple promise and I want to test if it has been resolved or rejected based on the input the promise takes.

var isPair = function(number) {
  var deferred = Q.defer();

  if (number % 2 == 0) {
    deferred.resolve(number + " is pair.");
  } else {
    deferred.reject(number + " is not pair.");
  }

}

it("rejects the promise when number is not pair", function() {
  return expect(isPair(1)).to.be.rejected;
}

My test returns true even when I set the param to 2 for example.

Can you give me an example of how I test if a promise resolved or rejected? If possible with the expect syntax please.

Thank you.

west
  • 35
  • 1
  • 8

2 Answers2

3

If you're using chai, you can install chai-as-promised to get the syntax you want:

it("rejects the promise when number is not pair", function() {
  return expect(isPair(1)).to.eventually.be.rejected();
});

Otherwise, you could use the done() callback supplied by mocha to indicate success/failure:

it("rejects the promise when number is not pair", function(done) {
  isPair(1).then(function() {
    done(new Error('Should have rejected'));
  },
  function() {
    done();
  });
});
Ben
  • 10,056
  • 5
  • 41
  • 42
2

Other answer is solid, alternatively you can do:

it("rejects the promise when number is not pair", function() {
    return isPair(1).then(Promise.reject, Promise.resolve);
});

This basically "inverts" the promise and expects the promise to reject (resolving it if it does, and rejecting if it doesn't).

Since you're using Q and not native promises or a new library:

it("rejects the promise when number is not pair", function() {
    return isPair(1).then(Q.reject, Q);
});

You don't really need the expect syntax here :)

Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
  • Hello, thanks for you reply. I really like the syntax of your second example, can you explain me please what the Q.reject and Q actually do? Thank you. – west May 06 '15 at 17:19
  • @west Q converts anything into a promise - even a rejected error so it recovers if there was an exception. Q.reject rejects whatever the promise was fulfilled with - so it's basically an "invert" - it turns fulfillments to rejections and vice versa. – Benjamin Gruenbaum May 06 '15 at 17:20