Cypress测试因应用未捕获TypeError失败,捕获逻辑为何不生效?
为什么Cypress中
err.message.includes("TypeError")无法捕获指定异常? 你的判断逻辑失效的核心原因是:异常信息里的"TypeError"属于错误类型标识,并非Error对象message属性的内容。
在JavaScript中,Error实例的message属性仅包含具体的错误描述文本(即Cannot read properties of undefined (reading 'links')),而"TypeError"这类错误类型存储在Error对象的name属性中。你当前的代码在message里查找"TypeError",自然匹配不到目标异常。
修正方案
方案1:通过err.name判断错误类型
直接针对错误类型属性做判断,这是最准确的方式:
import './commands' Cypress.on('uncaught:exception', (err, runnable, promise) => { if (err.message.includes("Unexpected token ':'")) { return false } // 检查错误类型是否为TypeError if (err.name === "TypeError") { return false } if (err.message.includes("Uncaught")) { return false } })
方案2:通过err.toString()匹配完整信息
Error对象的toString()方法会返回包含类型和描述的完整字符串(格式为"TypeError: xxx"),可以用这个方法来匹配:
import './commands' Cypress.on('uncaught:exception', (err, runnable, promise) => { if (err.message.includes("Unexpected token ':'")) { return false } if (err.toString().includes("TypeError")) { return false } if (err.message.includes("Uncaught")) { return false } })
额外说明
你代码中的第三个判断err.message.includes("Uncaught")同样不会生效,因为"Uncaught (in promise)"是浏览器对未捕获Promise异常的提示前缀,这部分内容并不存在于Error对象的message属性中。
内容的提问来源于stack exchange,提问作者Erenn
相关产品推荐
相关产品推荐

