javascript - Cypress : stub 打开的窗口

标签 javascript testing window.open stub cypress

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

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

现在我正在尝试 stub 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

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

最佳答案

下面的代码将帮助您 stub 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 Hook 中对 window.open 进行 stub ,这样可以帮助您在每次重新加载页面后生成新的窗口对象。但是,如果您想在现有选项卡而不是新选项卡中实际打开新 Url,您可以通过传递 "_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, ' _self'); 对于静态的,因此无论您单击哪个链接或按钮,触发 window.open,它们都将打开相同的 url。

关于javascript - Cypress : stub 打开的窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51747901/

相关文章:

javascript - setDefinitionFunctionWrapper() 如何在 Cucumber JS 中工作?

testing - 数据驱动测试方法和工具

PHPUnit 测试 - 无法断言实际大小 11935 与预期大小 3 匹配

javascript - 如何在 window.open 函数 ASP.NET 中调用 WebConfig appsetting 值?

javascript - 单击 fancybox2 外部

javascript - 这行代码是如何工作的? D3.js 不透明度函数

javascript - hammer js dragstart 不开火

ruby-on-rails - Rails - 出于测试目的实现可选片段缓存的最佳方法

javascript - window.open 没有应用给定的高度参数

javascript - 如果使用 jQuery 的方法,在新窗口上调用的 alert() 似乎是从原始页面调用的