在我的应用程序中有一个推荐列表,点击它会打开一个带有动态地址的新窗口:
$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/