There are a couple of key points worth noting:
It's important to understand that in a Cypress test, there are two window objects - the one the test operates in and the one the application operates in. When you use console.error('questo e errore')
, you are referring to the first window, while your spy is set on the second window.
Another crucial point is that test code executes faster than Cypress commands. This means that console.error('questo e errore')
may run before cy.visit()
completes.
Below are some examples that demonstrate these concepts:
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');
});