【发布时间】:2018-04-04 11:27:04
【问题描述】:
我有一段带有 jQuery ajax 调用的代码,如果出现 http 错误,则会引发异常。
function Locale)() {
$.ajax({
url: this.endpoint,
success: function(data) {
//do stuff
},
error: function(jqxhr, error, serverException) {
throw new httpErrorException(jqxhr, error, serverException);
}
});
}
我的异常很好,很简单,可以确保它正常工作
httpErrorException = function(jqxhr, error, serverException) {
this.toString = function() {
return error + ': ' + jqxhr.status + ' ' + serverException
}
}
我的测试如下
QUnit.test('test httpErrorException', function(assert) {
assert.expect(1);
server.respondWith('GET', '/fake/locale', [500, '', 'Internal Server Error']);
var done = assert.async();
assert.throws(
function() {
loc = locale(fakeUrl);
},
function(err) {
return err.toString() === 'error: 500 Internal Server Error';
},
'it failed'
);
done();
});
当我运行测试时,我得到了
Uncaught it failed
Expected: function( a ){
[code]
}
Actual: undefined
我一直在查看https://api.qunitjs.com/assert/throws 的 Qunit.throws 文档,看来我做的事情是正确的。我想这与异步调用有关,但我无法解决。
【问题讨论】:
标签: javascript unit-testing exception qunit