I've successfully implemented a script in Cypress that navigates to a specific URL with an onBeforeLoad function:
const bomMessage = cy.stub().as('bom');
cy.visit('https://helloworld.com', {
onBeforeLoad(win) {
win.addEventListener('message', (event) => {
if (event.data.event === 'ReadyToGo') {
bomMessage(event.data);
}
});
},
});
However, I encountered a scenario where I need the onBeforeLoad event to be triggered when clicking on a button named "Take me to next page" within the link of helloworld.com. My solution would be to possibly create the
onBeforeLoad(win) {
win.addEventListener('message', (event) => {
if (event.data.event === 'ReadyToGo') {
bomMessage(event.data);
}
});
},
as a command that can be called at any point in my script, waiting for it to occur or failing if not.
Is there a way to call the addEventListener function whenever needed during my test instead of having it inside the cy.visit call?
After receiving feedback:
Given('works', () => {
const bomMessage = cy.stub().as('bom');
cy.visit('https://helloworld.com')
cy.window().then((win) => {
win.addEventListener('message', (event) => {
if (event.data.event === 'ReadyToGo') {
bomMessage(event.data);
}
});
});
cy.get('@bom').should('be.calledOnce');
});