zl程序教程

您现在的位置是:首页 >  其他

当前栏目

Karma单元测试reload异常处理

2023-03-07 09:07:56 时间

业务逻辑中存在

window.location.reload();

运行测试用例,会出现

的错误,导致测试用例无法完整进行。

可以使用sinon来解决这个问题

window.onbeforeunload = sinon.spy();

但是如果,你需要在一个模块的测试用例跑完之后,刷新页面进行下一个测试用例,就不用使用这种方法,这时需要屏蔽代码中的刷新页面逻辑。参考官方文档

4. For all other cases, the Swiss army knife /* istanbul ignore next */ may be used which skips the "next thing" in the source code 5. The "next" thing may be, among other things: A JS statement (including assignments, ifs, loops, switches, functions) in which case all of the statement is ignored for all forms of coverage. A switch case statement, in which case the particular case is ignored for branch coverage and its contents ignored for all forms A conditional inside a ternary expression in which case the branch is ignored A part of a logical expression in which case that part of the expression is ignored for branch coverage

那么直接用

/* istanbul ignore next */
window.location.reload();

进行屏蔽,发现并不能解决问题。仔细读文档,(including assignments, ifs, loops, switches, functions) ,只能屏蔽赋值、ifs、循环、开关、函数。所以封装一个函数

/* istanbul ignore next */
export const locationReload = () => {
    /* istanbul ignore next */
    window.location.reload();
};

这样子就可以屏蔽刷新页面