我试图在使用mocha的异步承诺失败测试中断言正确的错误消息,但我的测试没有通过,我不知道为什么。
这里是代码 - 承诺是
'use strict';
let getFailingPromise = function() {
return new Promise(function(resolve, reject) {
// simply fail on the next tick
setTimeout(function() {
reject(new Error('No reason.'));
});
});
}
describe('failing promise catcher', function() {
it('should fail and I should catch it', function(done) {
let promise = getFailingPromise();
promise.catch(function(err) {
console.log('Error message:', err.message); // => Error message: No reason.
console.log(err.message === 'No reason.'); // => true
err.message.should.equal('No reason.');
done(); // => Never reached.
});
});
});
我知道Mocha无法捕获异步异常。但是上面的代码都是干净的,不会抛出任何错误 - 或者不应该有任何错误。
编辑:添加通话输出:
[zlatko@obelix ~/tmp]$ mocha test.spec.js
failing promise catcher
Error message: No reason.
true
1) should fail and I should catch it
0 passing (2s)
1 failing
1) failing promise catcher should fail and I should catch it:
Error: timeout of 2000ms exceeded
at null.<anonymous> (/usr/lib/node_modules/mocha/lib/runnable.js:158:19)
at Timer.listOnTimeout (timers.js:89:15)
我不理解什么?
答案 0 :(得分:1)
您可能没有加载should
来实现err.message.should.equal()
,因此运行时会抛出异常。
通常,.catch()
中抛出的异常将被忽略,除非您向您的承诺链添加另一个.catch()
子句(正如@Bergi在评论中所建议的那样)。
另一个选择是使用一个更精细的promises实现来警告你未处理的拒绝,比如bluebird
,它会告诉你:
Unhandled rejection TypeError: Cannot read property 'equal' of undefined
at ...
答案 1 :(得分:0)
你可以这样做:
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *simpleTableIdentifier = @"cellID";
FleetAccountCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil) {
cell = [[[NSBundle mainBundle] loadNibNamed:@"Your_nibName" owner:nil options:nil] objectAtIndex: 0];
}
[cell layoutIfNeeded];
return cell;
}