我需要在 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 代码的方法:ClientFunction和 t.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/