Cypress Trade-off — Opening multiple tabs.

Pushpapandey
2 min readJun 14, 2020

In my previous blog I have mentioned about the the Cypress Trade-off about opening multiple tabs in the browser. Since Cypress runs in the browser, it will never have multi-tabs support. However cypress has provided its Recipes which will make our tests very much better and very less flaky.

Problem Statement :

Most of the time this use case is needed when users click an <a> that opens a new tab. Users then want to switch to that tab to verify that the content loaded. And sometimes even navigate back and forth to these tabs.

Solution : Stubs & Spy APIs of Cypress.

Stub

Stub is a way to emulate the behaviour of an application.Instead of calling the real function, stub replace that one and return Canned Answers or some predefined object that we exactly know what will be returned. It is commonly used in Unit testing but nowadays it is also used to perform E2E tests with Cypress.io .

Syntax:

cy.stub()

cy.stub(object, method)

cy.stub(object, method, replacerFn)

Few rules associated with cy.stub()

cy.stub() requires being chained off of cy.

cy.stub() cannot have any assertions chained.

cy.stub() cannot time out.

Spy:

A spy gives you the ability to “spy” on a function, by letting you capture and then assert that the function was called with the right arguments, or that the function was called a certain number of times, or even what the return value was or what context the function was called with.

A spy does not modify the behavior of the function — it is left perfectly intact. A spy is most useful when you are testing the contract between multiple functions and you don’t care about the side effects the real function may create (if any).

Syntax :

cy.spy(object, method)

Few rules associated with cy.spy()

cy.spy() requires being chained off of cy.

cy.spy() cannot have any assertions chained.

cy.spy() cannot time out.

Example :

Usecase : main window -> new window -> main window

We can split up out tests into separate pieces and still have confidence that out application is covered.

1. Write a test to check that when performing the action in your app, the window.open event is called by using cy.spy() to listen for a window.open event.

cy.visit(‘http://localhost:3000', {

onBeforeLoad(win) {

cy.stub(win, ‘open’)

})}

// Do the action in your app like cy.get(‘.open-window-btn’).click()

cy.window().its(‘open’).should(‘be.called’)

2. In a new test, use cy.visit() to go to the url that would have opened in the new window, fill in the fields and click the buttons like you would in a Cypress test.

cy.visit(‘http://localhost:3000/new-window')

// Do the actions you want to test in the new window

Please visit here to learn about Stub & Spy in detail.

Thank you for reading this :)

--

--