What is the process for setting up onBeforeLoad as a command?

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

Answer â„–1

The onBeforeLoad hook prepares for the message event that occurs when the page is initially visited.

You have the flexibility to place it anywhere in the test before the action that triggers it, such as a button click.

All you need is access to the win object.

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

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

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Encountering a module not found issue while trying to

Attempting to test out 3 node modules locally by updating their source locations in the package.json files. The modules in question are sdk, ng-widget-lib, and frontend. ng-widget-lib relies on sdk, while frontend depends on ng-widget-lib. To locally build ...

What is the method for passing arguments in TypeScript functions?

Having an issue with a TypeScript method that I've written: createSomeData(args: { data: Data, helpfulInfo?: Info, context?: UIContext }): Promise<IDataModel>; The main problem I'm facing is that I can't seem to call it properly. I at ...

Selenium is having trouble locating elements by ID, class, or any other means. It seems that there are no iframes visible on

After searching through various questions and answers, I stumbled upon a query regarding Selenium being unable to locate an element by ID. The specific element in question is labeled "Add Parent": https://i.stack.imgur.com/AMHXf.png Despite trying differ ...

Developing interfaces for complex data structures in Angular and TypeScript使 can greatly improve code readability and

Lately, I've been investing a significant amount of time attempting to apply interfaces to the JSON response received from the API. Surprisingly, it works perfectly fine in the browser after compilation, but my IDE, VS Code, keeps throwing this error ...

Techniques for sharing type information between parent and child components in TypeScript

Imagine you have a Form with uncontrolled Input children like this: <Form initialValues={{ firstName: "", lastName: "", age: "" }}> <Input label="First name" name="firstName" /> <Input la ...

Having trouble accessing an https site in Internet Explorer while using BrowserMob proxy with Selenium

Encountering an issue when trying to open an https page in IE11 using browserMob and selenium. The error message received is "There is a problem with this website security certificate". In Chrome, the page works but there is a warning in the SSL certifica ...

Tips for displaying text on the bubbles of a vector map using the DevExpress library in an Angular and TypeScript environment to showcase counts or other relevant information

I managed to incorporate the devextreme angular 2 map into my demo project. My goal is to display the count of individuals with the name 'x' on the bubble as a label/text on the vector map, without the need for hovering to see a tooltip. I want t ...

Encountering TS 2694 Error while running the ng serve command

I'm encountering some troublesome errors while attempting to run my angular application. Honestly, I can't figure out what's wrong, so I'm hoping someone here can assist me. I didn't make any significant changes, just added a singl ...

Troubleshooting font color issues with PrimeNG charts in Angular

I have a chart and I am looking to modify the color of the labels https://i.sstatic.net/vsw6x.png The gray labels on the chart need to be changed to white for better readability Here is my code snippet: HTML5: <div class="box-result"> ...

After successfully logging in with Selenium and Python, I am unable to access Instagram pages

I am currently developing an Instagram bot that has a functionality called def nav_user. This function is designed to take me to a user's page, even if the login attempt fails due to incorrect credentials. When successfully implemented, it should gen ...

Tips for determining if the AA E-mail Address element is enabled or disabled

Hey there, I have the following HTML snippet: <td class="ms-crm-ReadField-Normal ms-crm-FieldLabel-RightAlign" id="agf_accountaccessemailaddressverified_c" title="AA E-mail Address Verified?"> <span class="ms-crm-InlineEditLabel"> ...

What is the reason behind TypeScript's decision to consider { ...Omit<Type, Missing>, ...Pick<Type, Add> } as Omit<Type, Missing> & Pick<Type, Add>?

I have been developing a versatile function that allows for adding fields one by one to partial objects of an unknown type in a strongly typed and safe manner. To illustrate, consider the following scenario: type Example = { x: string, y: number, z: boolea ...

What steps can be taken to resolve the "value" parameter exceeding the range error in Protractor?

Currently, I am utilizing Angular 7 in combination with Protractor for end-to-end automated test cases. Additionally, I have incorporated BrowserStack for testing my project across multiple browsers. Within my project, there is an image upload feature for ...

Tips for importing data extracted from an excel spreadsheet into a website using python's programming language

Objective: The task involves automating the process of pulling up a specific website, navigating to the inventory module, inputting SKU, quantity per box, and quantity of boxes, then clicking enter to print a label. I have successfully used Selenium' ...

Executing a series of HTTP requests sequentially using Angular 5

I need some guidance on sending an array of HTTP requests in sequential order within my application. Here are the details: Application Entities : Location - an entity with attributes: FanZone fanZone, and List<LocationAdministrator> locationAdmins ...

Tips for effectively implementing React.usecallback

Looking for a way to rewrite the handleClick method using React.useCallback in a function called Parent, which is triggered by a button click event in React and TypeScript. function Parent () { const [isOpen, setIsOpen] = React.useState(false); ...

How to optimize browser performance by setting maxInstances in ScalaTest Selenium

Our team utilizes a maven plugin to execute selenium tests with scala. The arguments provided are structured in the following manner: <argLine>-Dbrowser=chrome -Dwebdriver.chrome.driver=${project.basedir}/browser/drivers/chrome/2.25/mac64/chromedri ...

Include headless option when setting up Selenium Python with an extension

I am trying to integrate the i don't care about cookies extension into Selenium, but I keep encountering this error: selenium.common.exceptions.WebDriverException: Message: unknown error: failed to wait for extension background page to load: chrome-ex ...

Ways to update a property in a jQuery function

Is it possible to update the this.variable of the AuthDirective class using a jQuery function? I may have a basic question, but I need to trigger Jquery events and manipulate Angular variables. import { Component, Directive, OnInit } from '@angula ...

Method with undefined constructor parameter in Typescript

Understanding how to effectively use Typescript and Angularjs in conjunction has been a challenge for me. Despite reading numerous blog posts and consulting the official documentation for both projects, the concepts just haven't fully clicked. My Ang ...