使用QUnit/Sinon测试HTTP错误时抛出异常的异步Ajax调用
没问题,我来帮你搞定这个QUnit+Sinon的测试方案!核心思路是用Sinon的Fake Server模拟Ajax错误响应,精准验证自定义异常的抛出行为,下面是完整的实现和解释:
测试方案:验证Ajax错误时的自定义异常抛出
咱们的核心目标是:当Ajax请求返回HTTP错误时,代码要准确抛出httpErrorException,并且异常内容要和请求的错误信息匹配。
完整测试代码示例
// 确保已加载QUnit、Sinon、jQuery,以及你的业务代码(Locale函数和httpErrorException) QUnit.module('Locale Ajax Error Handling', { beforeEach() { // 初始化Sinon Fake Server,拦截所有Ajax请求 this.server = sinon.fakeServer.create(); }, afterEach() { // 测试结束后恢复原生Ajax,避免影响其他测试用例 this.server.restore(); } }); QUnit.test('should throw httpErrorException when Ajax returns HTTP 404 error', function(assert) { const done = assert.async(); // 标记这是异步测试,避免QUnit提前结束 // 1. 配置Fake Server,模拟HTTP 404错误响应 const testEndpoint = '/api/locale'; this.server.respondWith('GET', testEndpoint, [ 404, // HTTP错误状态码 {'Content-Type': 'application/json'}, // 响应头 'Resource Not Found' // 响应体内容 ]); try { // 创建Locale实例,手动指定测试用的endpoint const locale = new Locale(); locale.endpoint = testEndpoint; // 手动触发Fake Server的响应,把异步请求转为同步处理,方便捕获异常 this.server.respond(); // 如果走到这里,说明没抛出异常,测试失败 assert.ok(false, 'Expected httpErrorException to be thrown'); } catch (e) { // 2. 验证异常的类型和内容 assert.ok(e instanceof httpErrorException, 'Thrown exception should be instance of httpErrorException'); assert.strictEqual(e.jqxhr.status, 404, 'Exception should carry correct HTTP status code'); // 这里要和你自定义的toString逻辑匹配,假设你的toString是返回"error: 状态码 状态文本" assert.strictEqual(e.toString(), 'error: 404 Not Found', 'Exception toString returns correct formatted message'); } finally { done(); // 结束异步测试 } }); // 可扩展:复制上述用例,修改状态码(比如500)和响应内容,测试其他HTTP错误场景
关键部分解释
- Sinon Fake Server:
sinon.fakeServer.create()会拦截所有jQuery的Ajax请求,让咱们完全脱离真实后端,自定义响应内容,精准控制测试场景。 - 异步测试处理:用
assert.async()获取done回调,确保QUnit等待异步操作完成;this.server.respond()手动触发响应,把异步请求转为同步,方便捕获异常。 - 异常验证逻辑:在
catch块里要验证三个核心点:- 抛出的确实是咱们定义的
httpErrorException实例 - 异常携带了正确的HTTP状态码
- 异常的
toString()方法返回了预期的格式化错误信息(需和你自定义的逻辑匹配)
- 抛出的确实是咱们定义的
注意事项
- 确保Locale实例的
endpoint和测试里配置的URL一致,必要时可以手动修改实例的endpoint属性适配测试 - 如果你的
httpErrorException用到了serverException参数,记得在respondWith里设置对应的响应体,或者调整验证逻辑 - 建议为不同的HTTP错误(400、500、网络错误等)单独编写测试用例,覆盖全场景
内容的提问来源于stack exchange,提问作者Rob Cornelius
相关产品推荐
相关产品推荐

