Home > Enterprise >  How to create onBeforeLoad as a command?
How to create onBeforeLoad as a command?

Time:05-04

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');
});

CodePudding user response:

The onBeforeLoad hook is so that it's ready for message event that happens during the initial page visit.

But you can set it anywhere in the test before the trigger (in your case the button click).

You just need the win object.

cy.visit(...)                  // no listener here

cy.window().then(win => {
  win.addEventListener('message', (event) => {
    // set up the listener
  });
}

cy.get('my-button').click()  // triggers message event
  • Related