如何在Cypress中断言console.error被调用时参数含指定错误文本?
问题描述
我需要验证当初始化JSON缺少指定属性时,开发者控制台会输出指定错误信息。目前已设置spy监听win.console.error:
const onBeforeLoad = win => { cy.spy(win.console, 'error').as('consoleError'); }
测试中的断言代码如下:
cy.get('@consoleError').should('have.been.calledWith', 'aGivenErrorMsg');
但测试失败,因为Cypress日志中显示的实际错误信息被附加了额外文本,完整内容为:
aGivenErrorMsg at consoleError [as error] (https://test.com/__cypress/runner/cypress_runner.js:123270:26)
这些附加文本导致断言失败,需要验证Cypress生成的错误信息包含目标错误文本,该如何实现?
解决方案
以下几种方法可以实现模糊匹配错误信息,绕过Cypress附加的额外文本:
方法1:使用Sinon的stringContaining匹配器
借助Cypress集成的Sinon匹配器,直接断言调用参数包含目标文本:
cy.get('@consoleError').should('have.been.calledWith', Cypress.sinon.match.stringContaining('aGivenErrorMsg'));
方法2:使用正则表达式匹配
用正则表达式作为calledWithMatch的参数,匹配包含目标字符串的错误信息:
cy.get('@consoleError').should('have.been.calledWithMatch', /aGivenErrorMsg/);
方法3:手动检查调用参数
获取spy的调用记录,直接提取错误信息并验证是否包含目标文本:
cy.get('@consoleError').then(consoleErrorSpy => { const firstErrorMsg = consoleErrorSpy.firstCall.args[0]; expect(firstErrorMsg).to.include('aGivenErrorMsg'); });
内容的提问来源于stack exchange,提问作者Yu Zhang
相关产品推荐
相关产品推荐

