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

旧巷老猫 提交于 2019-12-03 04:25:09

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
    });
});

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();
});
SET

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.

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)
})

@Leonid's answer is correct, but you can simplify like so, and use only promises:

it('test promise with jasmine', function() {

    return getRejectedPromise().then(function() {
      // Promise should not be resolved, so we reject it
      return Promise.reject(new Error('Promise should not be resolved'));
    })
    .catch(function(err){
       if(!/Promise should not be resolved/.test(err && err.message)){
          return Promise.reject(err);
       }
    })
})
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!