如果诺言本身像“确实失败”测试中那样被拒绝,那么测试就会失败,正如我所期望的那样.如果断言失败/抛出错误/在promise的“ then”中拒绝了promise,我会记录错误:“未处理的promise拒绝”,并且测试仍然通过.如何使它在拒绝时失败,而不是记录未处理的拒绝?
import { expect } from 'chai';
describe.only('What?', () => {
const e = new Error('nopE');
it('does fail', () => Promise.reject(e));
it('should fail when rejected', () => {
const promise = new Promise(r => r());
promise.then(() => Promise.reject(e));
return promise;
});
it('should fail when thrown, then caught then rejected', () => {
const promise = new Promise(r => r());
promise
.then(() => { throw e; })
.catch(() => Promise.reject('huh'));
return promise;
});
it('should fail/reject when thrown, then caught then rethrown', () => {
const promise = new Promise(r => r());
promise
.then(() => { throw e; })
.catch(er => { throw er; });
return promise;
});
it(`doesn't matter if I expect`, () => {
const promise = new Promise(r => r());
promise.then(() => {
expect(1).to.eq(2);
});
return promise;
});
});
然后报告…
START:
What?
✖ does fail
✔ should fail when rejected
ERROR: 'Unhandled promise rejection', Error{stack: undefined}
✔ should fail when thrown, then caught then rejected
ERROR: 'Unhandled promise rejection', 'huh'
✔ should fail/reject when thrown, then caught then rethrown
ERROR: 'Unhandled promise rejection', Error{stack: undefined, line: 47567, sourceURL: 'http://localhost:9876/base/test/test_index.js?7f696b0b50c0a51c7a2fa5278582072b20241a3b'}
✔ doesn't matter if I expect
ERROR: 'Unhandled promise rejection', AssertionError{message: 'expected 1 to equal 2', showDiff: true, actual: 1, expected: 2, stack: 'AssertionError@http://localhost:9876/base/test/test_index.js?7f696b0b50c0a51c7a2fa5278582072b20241a3b:39222:25
解决方法:
您必须返回then(…)的返回值,而不是您创建的第一个承诺.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。