使用"Run all tests"时按标签(例如 cypress-grep)过滤测试



接着我的问题使用"运行所有测试"来筛选测试在Cypress 10+版本中,我们可以在Cypress GUI中应用标记的测试过滤器吗?

例如,如果我将cypress-grep添加到项目中,那么我可以对每个测试使用标记,如下所示

it('tests for smoke', {tags: ['@smoke']}, () => {
})
it('tests for fire', {tags: ['@fire']}, () => {
})

然后我可以从脚本运行npx cypress open --env grep=@smoke,grepFilterTests=true

是否可以扩展"使用筛选器运行所有测试"在GUI中输入标记@smoke并对冒烟测试进行临时运行?

我意识到上面的npx命令可以完成相同的工作,但是当我只想在开发更改期间运行我的烟雾时,这些步骤很长而且浪费时间。

可以通过标签动态过滤测试如果遵循使用@作为标签前缀的约定。

cypress-grep通常在cypress/support/e2e.js中调用,但是如果您在生成的测试脚本的顶部调用它也可以工作。

这是生成的测试的模式。前几行调用cypress-grep,通过标记@smoke启用过滤。

// generated script for specs filtered with "@smoke"
import cypressGrep from '@cypress/grep';
Cypress.env('grepTags', '@smoke');
cypressGrep();
context('cypress/e2e/login/login.cy.js', () => 
  require('../login/login.js'))
context('cypress/e2e/shopping-cart/checkout.cy.js', () => 
  require('../shopping-cart/checkout.cy.js'))

任务筛选规格

要动态地过滤标签,需要将cypress-grep的一些功能复制到项目代码中。

首先,你需要一个任务来找出哪些规格有你想要的标签。

module.exports = defineConfig({
  e2e: {
    setupNodeEvents(on, config) {
      on('task', {
        specsWithTag: async ({tag}) => {
          const {globbySync} = await import('globby')
          const specFiles = globbySync(config.specPattern, {
            cwd: __dirname,
            ignore: config.excludeSpecPattern,
          })
          const regex = new RegExp(`{\s*((tags)|(tag)):\s*[',"]${tag}[',"]\s*}`)
          return specFiles.filter(spec => {
            const fullPath = path.join(__dirname, spec)
            const specCode = fs.readFileSync(fullPath, { encoding: 'utf8' })
            return regex.test(specCode)
          })
        }
      })
      return config
    },
  }
})

测试生成器的更改

那么你需要增强_generate.cy.js规范来处理标签。

根据输入的过滤器,使用cypress-if可以很容易地分支代码。

import 'cypress-if'
const specExtension = '.cy.js'
const filter = Cypress.$(parent.document.body)
  .find('div#app')
  .find('#inline-spec-list-header-search')
  .val()
const specList = Cypress.$(parent.document.body)
  .find('div#app .specs-list-container ul:eq(0) 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) => {
    return item.text.endsWith(specExtension) && !item.text.startsWith('_')
  })
  .map((index,item) => item.path)
  .toArray()
const filterHasTag = (filter) => filter && filter.startsWith('@')
const generate = (specList, filter) => {
  const isTag = filterHasTag(filter)
  const indexSpecName = filter ? `_run-[${filter}]-${isTag ? 'tag' : 
    'filter'}${specExtension}` : `_run-all${specExtension}`
  const msg = `Processing ${isTag ? 'tag' : filter ? 'filter' : 'all'}: ${filter}`
  cy.log(msg)
  let content = `// generated script for specs filtered with "${filter}"nn`
  if (isTag) {
    content += `import cypressGrep from '@cypress/grep';n`
    content += `Cypress.env('grepTags', '${filter}');n`
    content += 'cypressGrep();nn'
  }
  content += specList.map(specPath => {
    return `context('${specPath}', () => require('..${specPath.replace('cypress/e2e', '')}'))`  
  }).join('n')
  cy.writeFile(`./cypress/e2e/_generated-tests/${indexSpecName}`, content)
}
it('', () => {
  cy.wrap(filterHasTag(filter), {log:false})
    .if()
    .task('specsWithTag', {specs: specList, tag: '@smoke'})
    .then(tagged => generate(tagged, filter))
    .else()
    .then(() => generate(specList, filter))
})

相关内容

最新更新