Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cypress: Stub open window

in my app there is an recommendations list, which on click opens a new window with a dynamic address:

$window.open(_shopURL, '_blank');

Now I'm trying to stub the windows.open event as shown in https://github.com/cypress-io/cypress-example-recipes/blob/master/examples/stubbing-spying__window/cypress/integration/window-stubbing.spec.js

Cypress.on('window:before:load', (win) => {
 win.open = cy.stub().as('windowOpen')
})


describe('Shop integration', () => {
 beforeEach(function () {
  cy.visitHome(countryCode, resellerId)
 })

it('can stub the window open event', function () {
  cy.get(`.recommendations-list .recommendations-cover:nth-of-type(1)`)
    .click()
  cy.get('@windowOpen').should('be.calledWith', 'page1.html')
})

But it's always opening the new tab and the logs are wrong: Cypress: stub open window

Does anybody has an idea why it's not working? Cheers!

like image 900
Flashed Avatar asked Aug 08 '18 13:08

Flashed


1 Answers

I'm using page-objects for every page I want to test. So in my parent page-object which gets inherited by every other PO I do the following when opening a url:

public navigateTo(url: string, defaultTimeout: number = 5000) {
    return cy.visit(url, {
        onBeforeLoad: (win: any) => {
            cy.stub(win, 'open');
        },
        timeout: defaultTimeOut
    });
}

This prevents window to open a new page.

like image 143
user3292546 Avatar answered Sep 22 '22 20:09

user3292546