Using Cypress with Typescript: Extracting values from aliases in cy.origin

I'm faced with a unique challenge where I need to extract data from an external source and incorporate it into my base URL. How can I remove the aliases that are causing errors whenever I try to call them? https://i.sstatic.net/gBmBW.png

Below is the script snippet that includes cy.origin():

// code snippet from the scenario

const credentials = {
            username: username,
            password: password,
        }
        cy.origin(Cypress.env(‘other’Url), { args: credentials }, ({ username, password }) => {
            cy.visit('/')
            cy.get('input[id="session_username"]').type(username)
            cy.get('input[id="session_password"]').type(password)
            cy.get('input[value="Log in"]').click()
            cy.wait(3000)
            // fetch details
            cy.get(‘<firstElementLocator>’).invoke('text').then((firstAlias) => {
                cy.wrap(firstAlias).as('firstAlias')
            })
            cy.get('<secondElementLocator>').invoke('text').then((secondAlias) => {
                cy.wrap(secondAlias).as('secondAlias')
            })
        })

// navigate to baseUrl

cy.visit('/')
cy.get(‘@firstAlias’).then((firstAlias) => {
    cy.get(‘@secondAlias’).then((secondAlias) => {
        var firstData = String(firstAlias)
        var secondData = String(secondAlias)
        cy.get(‘<thirdElementLocator>’).type(firstData)
        cy.get(‘<fourthElementLocator>’).type(secondData)
    })
})

Having considered @Fody's response (thank you Fody), I managed to resolve the error within the scripts. However, when I attempted to execute them, I encountered the following issue:

https://i.sstatic.net/afE64.png

Take a look at the configuration script: cypress.config.ts

let data: any
let key: any
let value: any
module.exports = defineConfig({
  e2e: {
    async setupNodeEvents(on: (arg0: string, arg1: any) => void, config: any) {
      // implement node event listeners here
      const bundler = createBundler({
        plugins: [createEsbuildPlugin(config)],
     });
     on('task', {
      setValue(key:any, value:any) {
        data[key] = value
        return null
      },
      getValue(key:any) {
        return data[key] || null
      },
    })
      on('file:preprocessor', bundler);
      await addCucumberPreprocessorPlugin(on, config);
      
      return config;
      
    },
    experimentalSessionAndOrigin: true,

Step implementation:

cy.get('table > tbody > tr:nth-child(1) > td:nth-child(2)').invoke('text').then((generatedSMN) => {
            cy.task('setValue', { key: 'generatedSMN', value: String(generatedSMN) })
        })

Answer №1

References were made to potential enhancements in the compatibility between base domain and origin, but for now, a temporary solution using tasks is provided.

cypress.config.js

const { defineConfig } = require("cypress");

const data = {}

module.exports = defineConfig({
  e2e: {
    setupNodeEvents(on, config) {
      on('task', {
        setValue({key, value}) {
          data[key] = value
          return null
        },
        getValue(key) {
          return data[key] || null
        },
      })
    },
    experimentalSessionAndOrigin: true,
  },
});

Test

cy.visit('http://example.com')

cy.origin('google.com', { args: credentials }, (credentials) => {
  cy.task('setValue', {key:'one', value:1})
})

cy.task('getValue', 'one')
  .as('firstAlias')
  .should('eq', 1)

Answer №2

@Fody's response is accurate, however, if you are encountering challenges while trying to implement the task, consider utilizing a fixture instead:

cy.visit(domain1)

cy.origin(domain2, { args: credentials }, (credentials) => {
  ...
  cy.get(selector).invoke('text').then(text => {
    cy.writeFile('./cypress/fixtures/first.json', text)
  })
})

cy.fixture('first.json').as('firstAlias')

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

Inconsistency with Angular 4 instance variables causes ambiguity within a function

Here is the code snippet: @Component({ selector: 'unb-navbar', templateUrl: './navbar.html' }) export class NavbarComponent implements OnInit { @Input() brand: string; controlador:boolean=false; overlay:string=""; @Input() menu ...

Can anyone advise on the best way to pass a function as a prop in React using TypeScript?

Hey there! I'm currently attempting to create a button component that can perform two separate actions: one labeled as "START" which initiates a countdown using StoreTimer.start(), and the other labeled as "RESET" which resets the countdown with Store ...

What is the best way to save the output of an asynchronous function into a class attribute?

Currently, I am attempting to retrieve HTML content from a webpage by utilizing a class equipped with a single asynchronous method. This process involves Typescript 3.4.3 and request-promise 4.2.4. import * as rp from 'request-promise'; class H ...

Enhance the capabilities of a basic object by incorporating a superclass through the creation of

I'm currently developing a library using Typescript 2.0 that can be utilized from both Typescript and JavaScript. Within the library, there is a class called Component and a function named registerComponent, both written in Typescript. My goal is to ...

Creating image paths for a list of items in reactjs can be achieved by mapping through the list

My goal is to display a list of items, with each item being assigned an image based on its ID: private static renderItemsTable(products: Product[]) { return <table className='table'> <thead> <tr> ...

The InAppBrowser seems to have trouble loading pages with cookies when I attempt to navigate back using the hardware back button

In my Ionic/Angular application, I utilize the InAppBrowser plugin to access a web application for my company. The InAppBrowser generally functions properly; however, there is an issue with a cookie within the web application that controls filters for cert ...

Explanation of TypeScript typings for JavaScript libraries API

Currently, I am in the process of building an Express.js application using TypeScript. By installing @types and referring to various resources, I managed to create a functional program. However, my main query revolves around locating comprehensive document ...

Encountering a 403 status code from the Spotify Web API while attempting to retrieve data using an OAuth 2.0 Token

I'm currently experimenting with the Spotify Web API and attempting to retrieve my most played songs. To obtain an access token for making requests, I am utilizing the client credentials OAuth flow. While I have successfully obtained the access token, ...

Use the any return type instead of unknown for untyped reducers

Currently in the process of refactoring a large redux state, I am facing an issue with reducers that have not yet been converted to typescript which are returning unknown instead of any. Is there a way to modify the default behavior of ReturnType? import ...

Type aliases using generics may demonstrate varying behaviors from type aliases without generics

Here is a code snippet to consider: type TestTuple = [ { test: "foo" }, { test: "bar"; other: 1; } ]; type Foo<Prop extends string> = TestTuple extends Record<Prop, string>[] ? true : fal ...

Converting input dates in nest.js using TypeScript formatting

Is it possible to set a custom date format for input in nest.js API request body? For example, like this: 12.12.2022 @ApiProperty({ example: 'ADMIN', description: 'Role name', }) readonly value: string; @ApiProperty({ ...

Tips for creating a custom script in my React Native application

My React Native app requires a script to generate static files during the release process. The app is a game that utilizes pre-computed boards, which are resource-intensive to compute. Therefore, I am developing a script that will create these boards and s ...

Angular: Generating components dynamically in HTML is unsuccessful

I possess the capability to dynamically generate components: import { Component, ComponentFactory, ComponentFactoryResolver, ComponentRef, OnInit, ViewChild, ViewContainerRef } from '@angular/core'; import { FilterComponent } from '../filter ...

I attempted to retrieve the id field of a jsonwebtoken following the user's login, but unfortunately, I was unable to access it

While working on the backend of my application, I encountered an issue trying to save the id field from a JSON Web Token (JWT) to an item that I created after a user logs in. Although I am able to log the JWT information successfully, I'm facing diffi ...

Error encountered in jquery.d.ts file: Unresolved syntax issue

I am currently in the process of transitioning my jQuery project into a Typescript project. I encountered an issue when attempting to include the jQuery typings from the DefinitelyTyped Github by using the following method: ///<reference path="../../ty ...

Incorporating Parse into Angular 2 using TypeScript

While I am aware that angular2 is still in beta, I decided to give it a try. I followed the angular2 quickstart guide available at https://angular.io/docs/js/latest/quickstart.html and everything seemed to be working fine. Now, I wanted to integrate Parse ...

Is TypeScript necessary, or can I simply stick with ES6?

As a client developer using AngularJS in my daily job, we are considering transitioning to TypeScript. After researching TypeScript, I discovered that most JavaScript packages I require need definition type files. This can be inconvenient, especially whe ...

The never-ending cycle of an Angular dropdown linked to a function being repeatedly invoked

I am currently working with a PrimeNg dropdown that is fetching its options through a function call. However, I have noticed that this function is being called an excessive number of times. Could this potentially impact the performance or any other aspect? ...

Ngx-toastr - Configure global settings for a particular toast message

Is it possible to define specific global settings for individual toast configurations? I am particularly interested in setting these configurations only for error toasts: { timeOut: 0, extendedTimeOut: 0, closeButton: true } I am aware that I can sp ...

Error in Typescript: The type 'string' cannot be assigned to the type '"allName" | `allName.${number}.nestedArray`' within the react hook form

Currently, I am tackling the react hook form with typescript and facing a challenge with my data structure which involves arrays within an array. To address this, I decided to implement the useFieldArray functionality. allName: [ { name: "us ...