I am in the process of writing a spec file with N it(s), where each it will visit a specific page of the application and will return the number of errors/warning in the applications.
I've posted also here: https://github.com/cypress-io/cypress/issues/4808
The solution offered does not seem to work:
it('should spy window.error', () => {
cy.visit('https://www.spiegel.de/', {
onBeforeLoad(win) {
cy.spy(win.console, 'error').as('spyWinConsoleError');
cy.spy(win.console, 'warn').as('spyWinConsoleWarn');
},
})
console.error('questo e errore')
cy.get('@spyWinConsoleError').should('be.calledOnce');
});
Any idea?
A couple of things to note,
there are two window objects in a Cypress test, the one the test runs in and the one the app runs in. Your call to console.error('questo e errore')
is to the first, but your spy is on the second.
test code runs faster than Cypress commands, so console.error('questo e errore')
is running before cy.visit()
gets done.
These example all work,
Spying on runner window console
it('should spy on RUNNER window.error', () => {
cy.spy(window.console, 'error').as('spyWinConsoleError');
console.error('questo e errore')
cy.get('@spyWinConsoleError').should('be.calledOnce');
});
Spying on app window console
it('should spy on APP window.error', () => {
const win = cy.state('window')
cy.spy(win.console, 'error').as('spyWinConsoleError');
win.console.error('questo e errore')
cy.get('@spyWinConsoleError').should('be.calledOnce');
});
Catching an actual app error
it('should spy window.error', () => {
cy.visit('../app/spy-on-win-error.html', {
onBeforeLoad(win) {
cy.spy(win.console, 'error').as('spyWinConsoleError');
},
})
cy.get('@spyWinConsoleError').should('be.calledWith', 'from app');
});
<body>
<script>
setTimeout(() => {
console.error('from app')
}, 1000)
</script>
</body>
Waiting for spiegel.de to load
it('should spy window.error', () => {
cy.visit('https://www.spiegel.de/', {
onBeforeLoad(win) {
cy.spy(win.console, 'error').as('spyWinConsoleError');
win.console.error("questo è l'errore due"); // call here after spy is set
},
})
cy.get('@spyWinConsoleError')
.should('be.calledOnce');
});