我试图找到一种方法来运行赛普拉斯单元测试时检查是否已将错误写入控制台。
我知道如何将某些内容记录到控制台
cy.log('log this to the console');
Run Code Online (Sandbox Code Playgroud)
但不是如何检查是否已写入错误。
有什么建议如何从(浏览器)控制台日志中读取错误?
注意:可能不是测试的“智能”方法,但有时我使用的js库会“抱怨”并将错误写入浏览器日志。这是为了简化测试。
小智 18
这正是我在控制台中捕获任何错误并断言日志计数所需要的。只需在其中添加以下内容cypress/support/index.js
Cypress.on('window:before:load', (win) => {
cy.spy(win.console, 'error');
cy.spy(win.console, 'warn');
});
afterEach(() => {
cy.window().then((win) => {
expect(win.console.error).to.have.callCount(0);
expect(win.console.warn).to.have.callCount(0);
});
});
Run Code Online (Sandbox Code Playgroud)
Lor*_*ren 14
自之前的答案以来,已经有了一些更新。
因为窗口是用 each 重新创建的cy.visit,赛普拉斯建议将存根作为cy.visit命令的一部分。
cy.visit('/', {
onBeforeLoad(win) {
cy.stub(win.console, 'log').as('consoleLog')
cy.stub(win.console, 'error').as('consoleError')
}
})
//...
cy.get('@consoleLog').should('be.calledWith', 'Hello World!')
cy.get('@consoleError').should('be.calledOnce')
Run Code Online (Sandbox Code Playgroud)
有关更多详细信息,请参阅有关删除控制台的官方常见问题解答:https : //docs.cypress.io/faq/questions/using-cypress-faq.html#How-do-I-spy-on-console-log
和配方库:https : //github.com/cypress-io/cypress-example-recipes/tree/master/examples/stubbing-spying__console
编辑:在无头模式下,以下内容不会直接登录到终端,但即使在AUT
console.error终端上,它也无法通过AUT的测试并间接显示错误消息,这可能是您想要的。
我不确定您的意思是什么,但是让我们遍历可以在赛普拉斯中记录输出的所有地方,以及如何处理几种情况。
要登录命令日志,请使用:
// from inside your test
cy.log('foo');
Run Code Online (Sandbox Code Playgroud)要登录devTools控制台:
// from inside your test
console.log('bar');
Run Code Online (Sandbox Code Playgroud)要登录terminal,您需要从赛普拉斯的节点进程中登录:
// from within e.g. your plugin/index.js file
console.log('baz');
Run Code Online (Sandbox Code Playgroud)(请注意,此处的AUT代表被测应用程序,表示您的应用程序)。
我还使用ansicolor包使终端中的错误变为红色,这是可选的。
// plugins/index.js
const ansi = require(`ansicolor`);
module.exports = ( on ) => {
on(`task`, {
error ( message ) {
// write the error in red color
console.error( ansi.red(message) );
// play `beep` sound for extra purchase
process.stdout.write(`\u0007`);
return null;
}
});
};
Run Code Online (Sandbox Code Playgroud)
注意:使用内部cy.now()命令来解决赛普拉斯Cypress detected that you returned a promise(IMO)不应抛出的趋势。
(改编自https://github.com/cypress-io/cypress/issues/300#issuecomment-438176246)
// support/index.js or your test file
Cypress.on(`window:before:load`, win => {
cy.stub( win.console, `error`, msg => {
// log to Terminal
cy.now(`task`, `error`, msg );
// log to Command Log & fail the test
throw new Error( msg );
});
});
Run Code Online (Sandbox Code Playgroud)
小智 5
目前没有直接的方法来完成您的要求,但已经就如何最好地获取此信息进行了一些很好的讨论。我在这里复制了一个解决方案,但如果您按照 github 链接,您可以看到其他解决方案。
此代码段取自此处找到的 github 问题:https : //github.com/cypress-io/cypress/issues/300
仅供参考,一个简单的解决方案就是监视控制台功能。
cy.window().then((win) => { cy.spy(win.console, "log") })每次调用该函数时都会打印命令日志,然后您还可以断言已记录的内容。
根据您为什么要断言出现问题的原因,另一种选择是以无头模式在测试下打印错误。工程副总裁为您创建了一个 NPM 包。
| 归档时间: |
|
| 查看次数: |
2875 次 |
| 最近记录: |