在 Cypress 版本 10+ 中使用“运行所有测试”过滤测试

Flo*_*e.P 8 cypress

Cypress v10 删除了运行所有测试的按钮。我们可以使用“桶”测试来解决这个问题,
参考Cypress 10 - 如何一次性运行所有测试?

// all.spec.cy.js

import './test1.spec.cy.js'    // relative paths
import './test2.spec.cy.js'
...
Run Code Online (Sandbox Code Playgroud)

但是是否可以搜索和过滤要运行的测试?

例如我们以前可以这样做:

Cypress v9 过滤测试

这会将选择范围从Run 250 集成规范缩减为Run 1 集成规范

除了手动设置多个桶规格外,有什么办法可以自动处理这个问题吗?

Fod*_*ody 7

我创建了一个生成过滤索引测试的测试。

它读取Cypress 运行程序的“搜索规格”字段及其下方的过滤规格列表。然后它编写一个新的索引规范,仅运行过滤后的规范。


执行

首先,创建一个文件夹cypress/e2e/_generated-tests。在该文件夹中,创建一个新规范_generate.cy.js

const filter = Cypress.$(parent.document.body)
  .find('div#app')
  .find('#inline-spec-list-header-search')
  .val()

const specPaths = Cypress.$(parent.document.body)
  .find('div#app')
  .find('ul').eq(0)
  .find('li')
  .map((index,el) => {
    const text = el.innerText.replace('\n', '').replace('\\', '/')
    const path = Cypress.$(el).find('a').attr('href').split('?file=')[1]
    return {
      text,
      path
    }
  })
  .filter((index, item) => item.text.endsWith('.cy.js') && !item.text.startsWith('_'))
  .map((index,item) => item.path)
  .toArray()

it('', () => {
  const indexSpecName = filter ? `_run-[${filter}]-filter.cy.js` : '_run-all.cy.js'

  const content = specPaths.map(specPath => {
    const relativePath = specPath.replace('cypress/e2e', '')
    return `context('${specPath}', () => require('..${relativePath}'))`  
  }).join('\n')

  cy.writeFile(`./cypress/e2e/_generated-tests/${indexSpecName}`, content)
})
Run Code Online (Sandbox Code Playgroud)

要使用它,首先运行_generate.cy.js规范。然后根据需要过滤规范树,并重新运行该规范。

它将创建一个_generated-tests名为 的新索引规范_run-[searchTerm]-filter.cy.js

此代码是根据我的喜好配置的,就像规范扩展一样.cy.js,但您可以调整以满足您自己的要求。


要使用cypress run排除所有生成的索引文件,请添加cypress/e2e/_generated-tests/**/*excludeSpecPattern配置中。