如何用Cypress测试拦截Zoom URL以避免打开应用弹窗?
解决Cypress测试中Zoom自定义协议链接拦截问题
问题根源
cy.intercept 只能捕获HTTP/HTTPS协议的网络请求,而Zoom的zoomus://属于自定义协议,这类跳转不会触发HTTP请求,所以用cy.intercept根本抓不到,自然不会生效。
解决方案
根据页面跳转Zoom链接的实现方式,分两种场景处理:
场景1:通过window.open打开Zoom链接
直接mock浏览器的window.open方法,捕获调用并阻止默认弹窗:
it.only('Should login and verify Zoom link is triggered without popup', () => { LoginPage.login(credentials.tester.username, credentials.tester.password); cy.url().should('eq', `${Cypress.config().baseUrl}/myaccount`); // Mock window.open,捕获Zoom链接并阻止弹窗 cy.window().then(win => { const openStub = cy.stub(win, 'open').callsFake((url) => { if (url.startsWith('zoomus://')) { expect(url).to.match(/^zoomus:\/.*/); return false; // 阻止默认打开行为,避免弹出对话框 } // 非Zoom链接保持原有行为(可选) return win.open.wrappedMethod.call(win, url); }).as('openStub'); }); MyAccount.clickFirstJoinViaZoomButton(); // 断言stub被调用,且参数符合Zoom协议格式 cy.get('@openStub').should('have.been.calledWithMatch', /^zoomus:\/.*/); });
场景2:通过<a>标签直接跳转(href为zoomus://)
如果按钮是直接绑定了href的a标签,需要拦截点击事件,阻止默认跳转同时验证链接:
it.only('Should login and verify Zoom link href without popup', () => { LoginPage.login(credentials.tester.username, credentials.tester.password); cy.url().should('eq', `${Cypress.config().baseUrl}/myaccount`); // 获取按钮元素,验证href并阻止默认跳转 myaccountLocators.firstJoinViaZoomButton().then($button => { // 先验证链接格式 cy.wrap($button).invoke('attr', 'href').should('match', /^zoomus:\/.*/); // 绑定点击事件阻止默认行为 cy.wrap($button).on('click', (e) => e.preventDefault()); }).click(); // 验证页面未跳转,会话正常运行 cy.url().should('eq', `${Cypress.config().baseUrl}/myaccount`); // 验证JS执行未停止 cy.window().then(win => { expect(win.document.body).to.exist; }); });
关键说明
- 两种方案都能避免浏览器弹出“打开zoom.us”的对话框
- 同时可验证链接确实是Zoom协议格式,且测试会话不会挂起、JS执行正常
- 若不确定页面跳转方式,可结合两种方案使用
内容的提问来源于stack exchange,提问作者PlexQ
相关产品推荐
相关产品推荐

