automationcypress

getting error after trying to calling function of other class in cy.origin()


[The error displayed in the image here ][1]I have a class file example1.js

class example1 {
getFunctionA(){
}
}

And in my other example2.js I imported example1.js and trying to call functions from example2.js inside the cy.origin but throwing error. The code I was trying in the example2.js is:

import example1 from '../example1.js'

class example2 {

describe('' ()=>{

const ex = new example1();

it('', ()=> {


    cy.origin('https://<example.com>/', ()=>{

        ex.getFunctionA()
        
    })

})

})
}

when I ran the code getting error at the line of calling function. can I get help how to import class and to access functions of other class inside cy.origin()

I tried using as below

    cy.origin('https://example.com/', {args: {ex}}, ({ ex })=>{
 
        ex.getFunctionA()
        
    })

but getting error as:

TypeError ex.getFunctionA is not a function


Solution

  • The cy.origin() command creates a sandboxed context that is isolated from the test context.

    This means that although you can pass parameters through to the origin's context, they can only be seriazable objects (or scalar variables), which means that functions or methods of classes cannot be passed in.

    But you can use the Cypress.require() command. It will only work if your class is in it's own file (not in the test).

    For example:

    cypress/support/Example-class.js

    class Example1 {
      getFunctionA() {
        return 42
      }
    }
    
    export default {
      Example1
    }
    

    spec.cy.js

    it('uses a local class in the origin command', () => {
      cy.visit('https://google.com');
    
      cy.origin('example.com', () => {
        const {Example1} = Cypress.require('../support/Example-class.js')
        
        const example1 = new Example1()
        const result = example1.getFunctionA()
        expect(result).to.eql(42)
      })
    })
    

    enter image description here

    You also need to enable this feature in cypress.config.js

    const { defineConfig } = require("cypress");
    
    module.exports = defineConfig({
      e2e: {
        experimentalOriginDependencies: true,          <-- enable Cypress.require()
    
        setupNodeEvents(on, config) {
        ...