在我的应用中,有一个建议列表,单击该列表会打开一个带有动态地址的新窗口:
$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
有人知道为什么它不起作用吗?
干杯!
最佳答案
我正在为每个要测试的页面使用页面对象。因此,在我的父页面对象(该对象被其他每个PO继承)中,我在打开URL时执行以下操作:
public navigateTo(url: string, defaultTimeout: number = 5000) {
return cy.visit(url, {
onBeforeLoad: (win: any) => {
cy.stub(win, 'open');
},
timeout: defaultTimeOut
});
}
这样可以防止窗口打开新页面。