2

I'm using Cypress to test a website.

When I use xpath inside cy.origin(), It's not working.

it('t1', function() {
    cy.origin(('BaseUrl'), () => {
        cy.visit('/profile')
        cy.xpath("//input[@name='username']").type('user')
        cy.xpath("//input[@name='password']").type('pass')
        cy.xpath("//button[@type='button']").click()
    })
})

Error:

TypeError
cy.xpath is not a function

Note that it works correctly outside cy.origin()

Fody
  • 23,754
  • 3
  • 20
  • 37

2 Answers2

1

TLDR: Stick with standard Cypress commands inside cy.origin().

It's a current limitation of cy.orgin(), in fact any custom command must be treated specially and cy.xpath() is a custom command.

See Callback restrictions

It is also currently not possible to use require() or dynamic import() within the callback. Because of this limitation, it cannot use npm packages or other third-party libraries inside the callback, as there is no mechanism to reference them. This functionality will be provided in a future version of Cypress.

While third-party packages are strictly unavailable, it is possible to reuse your own code between cy.origin() callbacks. The workaround is to create a custom Cypress command within the secondary origin in a before block:

before(() => {
  cy.origin('somesite.com', () => {
    Cypress.Commands.add('clickLink', (label) => {
      cy.get('a').contains(label).click()
    })
  })
})

it('clicks the secondary origin link', () => {
  cy.origin('somesite.com', () => {
    cy.visit('/page')
    cy.clickLink('Click Me')
  })
})

But you can't use this pattern with cy.xpath() as you currently need to require('cypress-xpath') and that can't be done inside cy.origin().


A Workaround

  1. Navigate to /node_modules/cypress-xpath/src/index.js

  2. Copy the entire contents

  3. Add a new command file in support: /cypress/support/xpath.js

  4. Add this to the file, pasting in the copied code

    before(() => {
      cy.origin('somesite.com', () => {  // your cross-origin URL here
    
         // paste here code from /node_modules/cypress-xpath/src/index.js
    
      })
    })
    
  5. Import xpath.js into /cypress/support/commands.js

Now cy.xpath() will work within cy.orgin() in any of your tests.

Fody
  • 23,754
  • 3
  • 20
  • 37
0

Check to see if non-xpath works.

cy.origin(('BaseUrl'), () => {
  cy.visit('/profile')
  cy.get("input[@name='username']").type('user')
  ...

If not, you've probably not set the experimentalSessionAndOrigin flag correctly.

  • Non-xpath works correctly, and I'm set xperimentalSessionAndOrigin in cypress.json as the following: { "experimentalSessionAndOrigin": true } – Fadi Alharthi Jun 02 '22 at 01:06