gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 20:33:39 25 4
gpt4 key购买 nike

我需要在我的 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

Error = 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com