测试是否在Nodejs中使用Jasmine解决或拒绝了承诺

che*_*kha 27 javascript node.js promise jasmine

我知道如何在摩卡中做到这一点,但想知道如何用Jasmine做到这一点.我试过这个

describe('test promise with jasmine', function() {
    it('expects a rejected promise', function() {
        var promise = getRejectedPromise();

        // return expect(promise).toBe('rejected');
        return expect(promise.inspect().state).toBe('rejected');
    });
});
Run Code Online (Sandbox Code Playgroud)

但是,状态总是如此pending,当然,测试失败了.我在网上找不到任何可以让它工作的例子.

有人可以帮我这个吗?

谢谢.

Leo*_*tny 38

要使用jasmine测试异步代码,您应该使用其异步语法,例如:

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
    });
});
Run Code Online (Sandbox Code Playgroud)

  • 从茉莉花^ 2.3版本开始,我无法将参数传递给done函数。最好使用`done.fail(new Error('error message')')。[参考文档](https://jasmine.github.io/2.3/introduction#section-54) (2认同)

nxm*_*mad 37

你现在可以使用 expectAsync()

期待成功:

it('expect result', async () => {
   ...
   await expectAsync(someAsyncFunction(goodInput)).toBeResolved(expectedResponse)
})
Run Code Online (Sandbox Code Playgroud)

预期失败:

it('expect result', async () => {
   ...
   await expectAsync(someAsyncFunction(badInput)).toBeRejectedWith(expectedResponse)
})
Run Code Online (Sandbox Code Playgroud)

  • 附加说明:*至关重要*始终*使用 `await` (`await ExpectAsync(...)`) - 否则测试将始终成功,无论 Promise 是否被拒绝,也无论是否测试预计它会被拒绝或解决! (2认同)
  • 这是最惯用的答案,应该被接受。(当前接受的答案在给出时很好,但您的解决方案现在客观上更好。) (2认同)

And*_*ang 6

jasmine 2.7以后支持返回承诺,并且将对其满足状态进行测试.

测试拒绝:

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

    throw new Error('Promise should not be resolved');
});
Run Code Online (Sandbox Code Playgroud)

还是:

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

为了验证实际的消息,除了通常之外instanceof/toBe(),放在catch:

expect(() => { throw err }).toThrow(new MyCustomError('Custom error message'));
Run Code Online (Sandbox Code Playgroud)

这种方法的好处是在测试输出上有一个更好的失败消息.

抛出MyCustomError的预期函数:自定义错误消息,但它抛出了另一条错误消息.

比通常的输出好一些.

测试已解决(不能更简单):

it('test promise with jasmine', async () => {
    await getRejectedPromise();
});
Run Code Online (Sandbox Code Playgroud)


SET*_*SET 5

您可以使用finally块来测试承诺状态:

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

您可以isFulfilled用来检查是否履行了承诺以及value检查履行价值的方法.相应的拒绝方法是isRejectedreason.

  • `finally()`,`isFulfilled()`不是标准的(截至2017年).请编辑您的答案以指定外部要求. (5认同)