【问题标题】:Cypress: Stub open windowCypress:存根打开窗口
【发布时间】:2019-01-15 18:58:23
【问题描述】:

在我的应用中有一个推荐列表,点击它会打开一个带有动态地址的新窗口:

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

现在我正在尝试存根 windows.open 事件,如 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')
})

但它总是打开新标签并且日志是错误的: Cypress: stub open window

有人知道为什么它不起作用吗? 干杯!

【问题讨论】:

  • 嗨,我正在尝试做完全相同的事情,但到目前为止没有成功。您找到解决此问题的方法了吗?

标签: javascript testing window.open stub cypress


【解决方案1】:

我正在为要测试的每个页面使用页面对象。因此,在我的父页面对象中,它被所有其他 PO 继承,我在打开 url 时执行以下操作:

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

这会阻止窗口打开新页面。

【讨论】:

    【解决方案2】:

    下面的代码将帮助您存根 window.open 并进一步断言该函数已被触发:

    it('opens the about page', () => {
      cy.visit('/')
      cy.window().then(win => {
        cy.stub(win, 'open').as('Open')
      })
      cy.get('.your-selector').click()
      cy.get('@Open').should('have.been.calledOnceWithExactly', yourUrl)
    })
    

    您也可以像以前一样在 cy.on 钩子中存根 window.open,这可以帮助您在每次重新加载页面后产生新的窗口对象。但是,如果您想在现有选项卡中实际打开新网址而不是新网址,您可以使用下面的代码,通过传递 "_self" 参数来覆盖旧的 "_blank"

    cy.window().then(win => {
              cy.stub(win, 'open').callsFake((url) => {
                return win.open.wrappedMethod.call(win, url, '_self');
              }).as('Open');
            });
    

    callsFake 函数 动态撤回已放入原 window.open(url, "_blank") 中的 url,或者您可以在 .call(win, url, ' 中手动更改 url _self'); 是静态的,所以无论你点击哪个链接或按钮,触发window.open,它们都会打开相同的url。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-28
      • 2016-07-14
      • 2014-08-07
      • 1970-01-01
      • 2012-11-07
      • 1970-01-01
      相关资源
      最近更新 更多