如何让Cypress浏览网站上的每个页面,看看是否有任何控制台错误,如果有,让运行测试的用户知道



我希望Cypress浏览网站上的每个页面,看看是否有任何控制台错误,如果有,让运行测试的用户知道。(我认为CSP检查会很有用,看看网站是否因为域没有被列入白名单而引发控制台错误。(

此程序包在控制台错误时失败可能使更容易

测试

import failOnConsoleError from 'cypress-fail-on-console-error';
failOnConsoleError();
const pages = [ "/page1", "/page2" ]
pages.forEach(page => {
it(`verifies the page ${page}`, () => {
cy.visit(page)                       
})
})

这里有一些关于Cypress和CSP的有趣内容

正在使用Cypress测试内容安全策略。。。几乎

您可以使用Cypress功能的组合来实现这一点。您可以将链接列表存储在一个字符串数组中,使用Cypress Lodash将每个字符串作为一个单独的测试进行迭代,并使用cy.visit()中的onBeforeLoad回调来监视console.error

describe('Tests', () => {
// Define links
const links = ['/1', '/2', '/3'...]
// Iterate through the links array using Cypress Lodash
Cypress._.times(links.length, (index) => {
it('validates site loads with no errors', () => {
cy.visit(links[index], {
// set the `onBeforeLoad` callback to save errors as 'error'
onBeforeLoad(win) {
cy.stub(win.console, 'error').as('error');
}
});
// Validate error was not called
cy.get('@error').should('not.have.been.called');
});
});
});

这个答案大部分都是从这个答案中得出的。

如果您想具体说明失败的错误,请尝试捕获uncaught:exception

Cypress.on('uncaught:exception', (err) => {
if (err.message.includes('Content Security Policy')) {
return true
} else {
return false  // only fail on the above message
}
})
describe('Testing Content Security Policy', () => {
const pages = [ "/page1", "/page2" ]
pages.forEach(page => {
it(`visiting page ${page}`, () => {
cy.visit(page)
})
})
})

相关内容

最新更新