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)
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)
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)
您可以使用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检查履行价值的方法.相应的拒绝方法是isRejected和reason.