【问题标题】:Filter tests by tags (e.g cypress-grep) when using "Run all tests"使用“运行所有测试”时按标签过滤测试(例如 cypress-grep)
【发布时间】:2022-11-12 14:31:56
【问题描述】:

继我的问题Filter tests using "Run all tests" in Cypress version 10+ 之后,我们可以将标记的测试过滤器应用于赛普拉斯 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 cypress-grep


    【解决方案1】:

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

    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('
    ', '').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}"
    
    `
      if (isTag) {
        content += `import cypressGrep from '@cypress/grep';
    `
        content += `Cypress.env('grepTags', '${filter}');
    `
        content += 'cypressGrep();
    
    '
      }
      content += specList.map(specPath => {
        return `context('${specPath}', () => require('..${specPath.replace('cypress/e2e', '')}'))`  
      }).join('
    ')
      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))
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-29
      • 1970-01-01
      • 2022-10-13
      • 2022-01-15
      相关资源
      最近更新 更多