如何重构QUnit与Sinon.js测试代码验证orientationchange触发页面重载?
问题分析与测试代码重构
咱们先拆解下原测试代码失效的核心原因:
- 你没有调用
readyFunction(),导致orientationchange的事件监听器根本没注册到window上,触发事件自然不会有反应 - 你把Spy挂在了
readyFunction本身上,但实际上我们要验证的是当orientationchange触发时,location.reload()被调用,而非readyFunction被执行 - 测试里的断言描述写的是"Two reloads triggered",但预期值是1,这明显是笔误
- 触发事件时附带的方向处理回调完全没必要,我们不需要处理方向逻辑,只需要触发事件就行
下面是重构后的完整测试代码:
QUnit.test("On 'orientationchange' reload is triggered", function (assert) { // 1. 先调用readyFunction,注册orientationchange事件监听器 readyFunction(); // 2. 用sinon监听location.reload方法,捕获它的调用情况 const reloadSpy = sinon.spy(location, 'reload'); try { // 3. 触发window的orientationchange原生事件 window.dispatchEvent(new Event('orientationchange')); // 4. 断言reload方法被调用了一次 assert.equal(reloadSpy.callCount, 1, "reload should be triggered once when orientation changes"); } finally { // 5. 还原被监听的reload方法,避免污染其他测试用例 reloadSpy.restore(); } });
额外补充说明
- 这里用原生的
window.dispatchEvent触发事件,比jQuery的trigger更贴合真实场景;如果你的项目依赖jQuery,换成$(window).trigger('orientationchange')也可以正常工作 - 用
try/finally包裹断言逻辑,是为了确保不管测试成功还是失败,被Spy的方法都会被还原,防止影响后续测试 - 你的原函数里并没有根据设备方向做分支处理,所以不需要模拟
window.orientation的值,只需要验证重载行为即可
内容的提问来源于stack exchange,提问作者Nixen85
相关产品推荐
相关产品推荐

