0

I use chai-as-promised library with promise generated by the q library. This simple test case should work (the promise must be rejected) or i misunderstand promise feature?

bdd.it("Test rejection", function () {
    var promise = q.promise(function (resolve, reject, notify) {
        reject(new Error("test"));
    }).then(function () {
        // Nothing to do
    });
    promise.should.be.rejectedWith(Error);
    return promise;
});

This test fail with Error: test (I use Intern as unit test library) althought the below test pass:

bdd.it("Test rejection", function () {
    var promise = q.promise(function (resolve, reject, notify) {
        reject(new Error("test"));
    }).should.be.rejectedWith(Error);
    return promise;
});
Troopers
  • 5,127
  • 1
  • 37
  • 64

1 Answers1

1

The library needs you to return the return value of .rejectedWith() in order for it to test the assertion. You're just calling .should.be.rejectedWith() in the middle of your test, and it can't do anything with that.

If you look at the documentation for chai-as-promised, you can see that this is precisely what they are doing in their examples:

return promise.should.be.rejectedWith(Error); 

The same is true for other promise-based assertions like .should.become().

Your second test is correct. You can also just use return instead of assigning the result to a variable first:

bdd.it("Test rejection", function () {
    return q.promise(function (resolve, reject, notify) {
        reject(new Error("test"));
    }).should.be.rejectedWith(Error);
});
JLRishe
  • 99,490
  • 19
  • 131
  • 169
  • Ok but so how to check several conditions like rejected and error with code equal to 31 for sample? – Troopers Mar 16 '17 at 13:02
  • @Troopers I'm not sure, but I think you could do `return q.promise(.....).catch(function (error) { /* perform ordinary assertions on error */ });` – JLRishe Mar 16 '17 at 13:20