我有javascript代码,如果它在浏览器中运行会引发警报,但是当我运行单元测试时我不想提出警报.
我试着用一条线来解决这个问题
if( allowAlerts === false ){
alert = console.log;
}
Run Code Online (Sandbox Code Playgroud)
但是当我跑的时候
alert("This bad thing happened");
Run Code Online (Sandbox Code Playgroud)
我回来了
TypeError: Illegal invocation
Run Code Online (Sandbox Code Playgroud)
直接重新分配警报是一个kludgey解决方案,我可以通过其他方式轻松解决问题,但我以前从未遇到过非法调用错误,并希望有人能够解释它的含义.
该console.log函数需要其调用上下文作为控制台.
使用
alert = console.log.bind(console);
Run Code Online (Sandbox Code Playgroud)
或者,如果您想与旧IE兼容:
alert = function(){ console.log.apply(console, arguments) };
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4605 次 |
| 最近记录: |