javascript - 如何用TestCafe实现window.onerror?

标签 javascript testing error-handling e2e-testing testcafe

我需要在 TestCafe 测试中抑制错误(该错误来自模拟页面)。示例代码:

function stoperror() {
            try {
                this.clickMockContinueButton();
             } catch(e) {
                console.log(e)
             } 
            return true;
        }

Call it:

window.onerror = stoperror;

虽然我添加了Node窗口包:https://www.npmjs.com/package/window

错误 = ReferenceError:窗口未定义

最佳答案

TestCafe 仅提供两种在浏览器中执行 JavaScript 代码的方法:ClientFunctiont.eval 。例如,如果您想通过 window.onerror 属性安装全局错误处理程序,则可以使用以下代码:

const installErrorHandler = ClientFunction(() => {
   window.onerror = error => {
       // handle error here
   };
});

test('Install the error handler', async t => {
    await installErrorHandler();
});

但我应该警告您,如果您警告抑制其他问题中描述的错误,则此方法将不起作用: TestCafe ClientFunction TypeError error as document is undefined

此问题的错误发生在 ClientFunction 上下文中,并且无法传播到全局错误处理程序。如果您想抑制 ClientFunction 实例中发生的错误,请使用 try ... catch 语句将代码包装在其主体内:

const dangerousFunction = ClientFunction(() => {
    try {
        // dangerous code
    }
    catch (e) {
        // handle error
    }
});

关于javascript - 如何用TestCafe实现window.onerror?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57362305/

相关文章:

javascript - 使用 foreach 通过 Ajax 和动态表单进行发布

javascript - 自动向左对齐图像网格

javascript - CSS 变换 :rotateX for Internet Explorer

testing - Protractor "restartBrowserBetweenTests: true"重新启动浏览器,但在此之后不要运行测试

c# - 使用自定义错误页面捕获错误

algorithm - 创建反向链表

javascript - 如何在 php 中使用 jquery 更新当前日期

java - 开始使用 TestFx

.net - 如何测试执行 ftp 下载和数据库插入的应用程序?

c - 处理 C 只读文件关闭错误