I have created a script that is navigating to a URL with a onBeforeLoad using Cypress:
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);
}
});
},
});
But here is my problem, I have a scenario where I enter a url e.g. helloworld.com and inside the link there is a button called "Take me to next page" - when i'm clicking on that button, then I want the onBeforeLoad to be triggered. My idea was to perhaps be able to make the
onBeforeLoad(win) {
win.addEventListener('message', (event) => {
if (event.data.event === 'ReadyToGo') {
bomMessage(event.data);
}
});
},
as a command which I can call whenever I want in my script that waits for it to happen else fails.
Is it possible to make the addEventListener to be called whenever I want in my test instead of having it inside the cy.visit call?
EDITED after answer:
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');
});