Test if a promise is resolved or rejected with Jasmine in Nodejs

To test asynchronous code with jasmine you should use its async syntax, e.g.:

describe('test promise with jasmine', function(done) {
    var promise = getRejectedPromise();

    promise.then(function() {
      // Promise is resolved
      done(new Error('Promise should not be resolved'));
    }, function(reason) {
      // Promise is rejected
      // You could check rejection reason if you want to
      done(); // Success
    });
});

You can use finally block to test promise state:

it('should resolve if auth succeed', (done)=>{
    var p = server.login('user', 'password');
    p.finally(()=>{
        expect(p.isFulfilled()).toBeTruthy();
        done();
    });
});

You can use isFulfilled to check if promise was fulfilled and value method to check the fulfillment value. Corresponding methods for rejection are isRejected and reason.


jasmine 2.7 onwards supports returning promises, and would have its fulfilled state tested.

To test for rejection:

it('test promise with jasmine', async () => {
    try {
        await getRejectedPromise();
    } catch (err) {
        return;
    }

    throw new Error('Promise should not be resolved');
});

or yet:

it('test promise with jasmine', async () => {
    await getRejectedPromise()
        .then(
            () => Promise.reject(new Error('Promise should not be resolved')), 
            () => {});
});

To verify the actual message, besides the usual instanceof/toBe(), place inside the catch:

expect(() => { throw err }).toThrow(new MyCustomError('Custom error message'));

The benefit from this approach is to have a nicer fail message on the test output.

Expected function to throw MyCustomError: Custom error message, but it threw Another error message.

Somewhat better than the usual output.

To test for resolved (can't be simpler):

it('test promise with jasmine', async () => {
    await getRejectedPromise();
});

you can now use expectAsync()

Expecting success:

it('expect result', async () => {
   ...
   await expectAsync(someAsyncFunction(goodInput)).toBeResolved(expectedResponse)
})

Expecting failure:

it('expect result', async () => {
   ...
   await expectAsync(someAsyncFunction(badInput)).toBeRejectedWith(expectedResponse)
})