Javascript 在 Nodejs 中使用 Jasmine 测试承诺是否已解决或拒绝
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27164404/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Test if a promise is resolved or rejected with Jasmine in Nodejs
提问by chepukha
I know how to do it in Mocha but want to know how to do it with Jasmine. I tried this
我知道如何在 Mocha 中做到这一点,但想知道如何用 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');
});
});
However, the state is always pendingand, of course, the test fails. I couldn't find any example online that I could make it work.
然而,状态总是如此pending,当然,测试失败了。我在网上找不到任何可以使它工作的示例。
Can someone please help me with this?
有人可以帮我解决这个问题吗?
Thanks.
谢谢。
回答by Leonid Beschastny
To test asynchronous code with jasmine you should use its async syntax, e.g.:
要使用 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
});
});
回答by nxmohamad
you can now use expectAsync()
你现在可以使用 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)
})
回答by André Werlang
jasmine 2.7 onwards supports returning promises, and would have its fulfilled state tested.
茉莉花 2.7 以后支持返回承诺,并且会测试其已完成状态。
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:
要验证实际消息,除了通常的instanceof/toBe(),放置在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.
预期函数会抛出 MyCustomError: 自定义错误消息,但它抛出了另一个错误消息。
Somewhat better than the usual output.
比通常的输出要好一些。
To test for resolved (can't be simpler):
测试已解决(再简单不过了):
it('test promise with jasmine', async () => {
await getRejectedPromise();
});
回答by SET
You can use finallyblock to test promise state:
您可以使用finally块来测试承诺状态:
it('should resolve if auth succeed', (done)=>{
var p = server.login('user', 'password');
p.finally(()=>{
expect(p.isFulfilled()).toBeTruthy();
done();
});
});
You can use isFulfilledto check if promise was fulfilled and valuemethod to check the fulfillment value. Corresponding methods for rejection are isRejectedand reason.
您可以使用isFulfilled来检查承诺是否已履行以及value检查履行值的方法。相应的拒绝方法是isRejected和reason。
回答by Alexander Mills
@Leonid's answer is correct, but you can simplify like so, and use only promises:
@Leonid 的回答是正确的,但您可以像这样简化,并且只使用承诺:
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);
}
})
})

