Handle Multi-Domain or Cross-Origin in Cypress

Waris Jamal
3 min readJun 27, 2022

--

In order to test the e2e functionality of your product, you might often need to visit multiple domains in a single test case and If you choose Cypress then it becomes very difficult to accomplish this before Cypress version 9.6.0. This article will cover all the problems and solutions that you may encounter when working with multiple domains.

Test Case:

  1. Go to TechEdClasses
  2. Reach to Notes > Class X
  3. Click on the YouTube link. (Cross-Origin Error occurs)
  4. Verify and click on the playlist title.

The Problem

So till cypress updated 9.6.0, we had to write complex code to accomplish cross-Domain functionality because Cypress runs inside the browser, and tests that execute commands against multiple superdomains fail due to the same-origin rule. As an example of a cross-origin error, the following test will fail:

cypress-cross-domain-error-code
cypress-cross-domain-error

Therefore, this problem occurs while switching from one domain to another. The reason we are facing this issue in the above example is because we are switching from TechEdClasses to YouTube in the same test case.

What is Cross-Origin

When a domain name, hostname, and port are the same, it is said to be “same-origin”. Everything else is called “cross-origin”.

cross-origin-example

The Solution

The solution to this problem is in cypress version 9.6.0. cy.origin() which allows you to execute commands against any number of superdomains, all within a single test case.

In order to use cy.origin(), the experimentalSessionAndOriginflag must be set to truein the Cypress configuration file(cypress.config.js).

Syntax

cy.origin(url, callbackFn)
cy.origin(url, options, callbackFn)

Now in our test case, we need to do some modifications for solving this issue. The following example fixes the failing test we mentioned in the problem section:

Step: 1- Add experimentalSessionAndOrigin:true in cypress.config.js file.

cypress.config.js

Step: 2- Addcy.origin() in your test case and visit the URL.
Note: Listed here is one of the ways you can use it, but there are other ways as well, for more information visit cypress.io.

crossOrigin.cy.js

Test Runner Window

If you want to resolve the promise/want to pass the variable in cy.origin() then you can use the below mentioned way.

Thank you for reading the article and if you have any suggestions please put them in a comment. If you find it useful, please clap.

Conclusion

Cypress made so many improvements to solve our problems after the update. Many things have changed in Cypress update 10.0.0, so please let us know if you find any issues.

--

--