Overcoming Cypress trade-offs with a single trick

The permanent trade-offs of Cypress are listed here. Pay extra attention to the last three points since the first two may not be the blocker in most cases if you are okay with Javascript. However, we expect the ones listed below to be part of the test framework if we are coming from a traditional test automation environment:

  • There will never be support for multiple browser tabs.
  • You cannot use Cypress to drive two browsers at the same time.
  • Each test is bound to a single origin. 1

Synchronizing Cypress with another back-end process, such as Puppeteer, is possible to drive a second browser or connect to the existing one. The same documentation mentions the workaround briefly. Let's unwrap the solution with examples.

Ensure that the Cypress is available and initiated with the standard project structure. Additionally, install Puppeteer with npm. However, you can choose any other tool you know the best.

Navigate to the plugins cypress/plugins/index.js file and add a task with Puppeteer setup. The args array is where we specify any browser flags we may need for our application.

Puppeteer setup in Cypress plugins

We'll also need to connect the previously opened browser. For example, Imagine that a Puppeteer user sent a message in the group chat. A Cypress user received it and sent their own. To continue the interaction, we need to get back to the same browser page in Puppeteer. We need to connect each time we return to the Puppeteer user.

Connecting to previously opened browser

Let's try to open a new browser instance with any URL we want, even in the same test block. We have a new browser instance on which we interact with the Puppeteer.

Opening new browser instance

There is a way to connect to the Cypress browser instance as well. Add the below code to get the proper debugging port.

Getting Cypress debugging port

Add a few Puppeteer tasks to interact with the Cypress browser instance. The first one connects to Cypress's page and gets the current URL for later assertion. The second one opens up a new tab in the Cypress browser.

Puppeteer tasks for Cypress browser interaction

The actual tests will look like this. The below assertion is entirely unnecessary. However, it is there to showcase how we can check the information returned from the task. It also shows that Puppeteer connected to the Cypress browser successfully.

Example test with assertions

Puppeteer comes with options to retrieve performance metrics from the page. Even if you don't need a second browser, try connecting to the Cypress browser and get some web performance metrics for assertions. Have fun! Review the final files for more experimentation.

Footnotes

  1. Multi-domain now supported - Cypress 9.6.0: Easily test multi-domain workflows with cy.origin