Fla*_*hed 12 javascript testing stub window.open cypress
在我的应用程序中有一个推荐列表,单击该列表会打开一个带有动态地址的新窗口:
$window.open(_shopURL, '_blank');
Run Code Online (Sandbox Code Playgroud)
现在我正在尝试存根 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')
})
Run Code Online (Sandbox Code Playgroud)
但它总是打开新选项卡并且日志是错误的: Cypress:stub open window
有人知道为什么它不起作用吗?干杯!
小智 11
下面的代码将帮助您存根 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)
})
Run Code Online (Sandbox Code Playgroud)
您还可以像您一样在cy.on挂钩中存根window.open,这有助于您每次在页面重新加载后生成新的窗口对象。但是,如果您想在现有选项卡中实际打开新 Url 而不是新选项卡,您可以通过传递“_self”参数来使用下面的代码来覆盖旧的“_blank”:
cy.window().then(win => {
cy.stub(win, 'open').callsFake((url) => {
return win.open.wrappedMethod.call(win, url, '_self');
}).as('Open');
});
Run Code Online (Sandbox Code Playgroud)
CallsFake 函数动态撤回已放入原始 window.open(url, "_blank") 中的 url,或者您可以手动更改 .call (win, url, '_self'); 中的 url;使用静态链接,因此无论您单击哪个链接或按钮,都会触发 window.open,它们都会打开相同的 url。
小智 5
我对我想要测试的每个页面都使用页面对象。因此,在我的父页面对象(被所有其他 PO 继承)中,我在打开 url 时执行以下操作:
public navigateTo(url: string, defaultTimeout: number = 5000) {
return cy.visit(url, {
onBeforeLoad: (win: any) => {
cy.stub(win, 'open');
},
timeout: defaultTimeOut
});
}Run Code Online (Sandbox Code Playgroud)
这可以防止窗口打开新页面。
| 归档时间: |
|
| 查看次数: |
17116 次 |
| 最近记录: |