首页 > 解决方案 > Cypress - 添加handelExpection 代码但仍无法捕获应用程序异常

问题描述

我正在尝试测试此站点https://store.google.com/regionpicker,例如,当我选择一个地区(美国)并重定向到此 URL 时:https://store.google.com/us/? hl=en-US®ionRedirect=true我在控制台中收到应用程序错误,并且 cypress 无法继续

我在测试开始之前添加了这段代码来处理异常,但它没有捕获它:


    cy.on('uncaught:exception', () => {
          return false
        })

完整代码:

describe('Purchase a device from Google Store', () => {

const LOCATORS = {
    devicesMenu: '[id="desktop-products"]',
    headerContainer: '.header-container',
    regionTitle: '.region-title',
    dialog: '[role="dialog"]',
    button: '[role="button"]',
}

before(() => {
    cy.visit('/')
})

beforeEach(() => {
    Cypress.on('uncaught:exception', () => {
        return false
    })
})

it('Purchase device', () => {
    let region = 'United States'
    let urlToVerify = 'us/?hl=en-US&regionRedirect=true'

    cy.contains(LOCATORS.regionTitle, region)
    .click().then(() => {
        cy.get(LOCATORS.dialog).within(() => {
        cy.contains('Continue')
            .click({ force: true }).then(() => {
                cy.url()
                .should('include', urlToVerify)
            })
    })
    })
})

})

在此处输入图像描述

在此处输入图像描述

标签: cypress

解决方案


您可以在事件的事件处理程序中测试 URL url:changed

基本问题似乎是无法将 Cypress 带到https://store.google.com,浏览器以 URL 结尾about:blank

但是通过向您添加侦听器,url:changed您至少可以验证是否尝试了正确的 URL。

it('redirects after region select', () => {

  const region = 'United States'
  const urlToVerify = 'us/?hl=en-US&regionRedirect=true'

  cy.on('url:changed', (url) => {
    expect(url).to.include(urlToVerify)   // use chai to assert
  })

  cy.contains(LOCATORS.regionTitle, region).click()
  cy.get(LOCATORS.dialog).within(() => {
    cy.contains('Continue').click({ force: true })
  })
})

推荐阅读