【问题标题】:How to implement async await in Cypress test?如何在赛普拉斯测试中实现异步等待?
【发布时间】:2023-02-25 18:22:29
【问题描述】:

我有一个带有一些重复测试的规范文件,我需要创建一个循环来避免这种重复。但是 JS 的异步特性使它成为不可能。我想我需要使用 async await 或 promises 而不是现有的解决方案,但我不知道如何实现它。有人可以建议吗?

这是来自现有规范的代码 sn-p,它产生 9 个测试(实际上每个测试套件 5 个 it())。问题是这 9 个测试中的每一个都使用在开关的最后一个分支(案例 9)中定义的相同数据。这意味着 switch 的所有分支都被执行,然后测试才开始具有最后一个分支值集。最后,所有这 9 个测试(测试套件)都是执行了 9 次的相同测试(测试套件)。

for(let i = 0; i < 9; i++) {
  switch(i) {
    case 0:
      name = 'name 0'
      url = 'url 0'
      product = 'product 0'
      isMultipleProductsDropdown = true / false
      stateDropdownSelector = '#selector 0'
      store = 'store name 0'
      storeDisplayed = 'store displayed 0'
      billingAddressLabel = 'billingAddressLabel 0'
      status = 'status 0'
      break
    ..............
  case 9:
    name = 'name 9'
    url = 'url 9'
    product = 'product 9'
    isMultipleProductsDropdown = true / false
    stateDropdownSelector = '#selector 9'
    store = 'store name 9'
    storeDisplayed = 'store displayed 9'
    billingAddressLabel = 'billingAddressLabel 9'
    status = 'status 9'
    break
  }

  context('context 1', () => {
    it('Test 1-1', () => {
      ..................
    })
    
    it('Test 1-2', () => {
      ..................
    })
  })

  context('context 2', () => {
    it('Test 2-1', () => {
      ..................
    })
    
    it('Test 2-2', () => {
      ..................
    })

    it('Test 2-3', () => {
      ..................
    })
  })
}

【问题讨论】:

    标签: javascript async-await cypress


    【解决方案1】:

    我不明白你为什么会遇到这个问题,从逻辑上讲代码看起来没问题。

    但是我可以建议将数据移到循环之外吗(即删除开关)。这种方式在 Cypress 文档中更为传统。

    const datas = [
      {
          name : 'name 0'
          url : 'url 0'
          product : 'product 0'
          isMultipleProductsDropdown : true,
          stateDropdownSelector : '#selector 0'
          store : 'store name 0'
          storeDisplayed : 'store displayed 0'
          billingAddressLabel : 'billingAddressLabel 0'
          status : 'status 0'
      },
      {
          name = 'name 9'
          ...
      }
    ]
    
    datas.forEach((data,i) => {
    
      context(`context ${i}`, () => {
        it(`Test ${i}-1', () => {
    
          // extract the data values  
          const {name, url, product, isMultipleProductsDropdown, etc } = data
    
          ..................
        })
        
        it(`Test ${i}-2`, () => {
    
          // extract the data values  
          const {name, url, product, isMultipleProductsDropdown, etc } = data
    
          ..................
        })
      })
    })
    

    "context(context ${i}, () => {" 等使用反引号和${} 将索引号插入到字符串中。

    数据可以在单独的夹具文件中,如果愿意,可以将其读入测试。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-15
      • 1970-01-01
      • 2020-05-09
      • 1970-01-01
      • 2022-10-02
      • 1970-01-01
      相关资源
      最近更新 更多