首页 > 解决方案 > 如何在 Cypress 中使用不同的夹具运行相同的测试?

问题描述

我正在尝试对显示在两个单独页面上的组件运行完全相同的赛普拉斯测试。为了实现这一点,我想我会使用一个forEach语句,以便为每个“状态”运行相同的代码(参见下面的代码)。

问题是语句中的代码块在状态 #1 的测试完成之前before开始为状态 #2 运行。这导致状态#1 的测试失败(因为它具有状态#2 固定装置)。

如何使before状态#2 的部分等待状态#1 中的所有测试完成?

const states = [
  { 
    "startPath": "/path1", 
    "fixture": "fixture1"
  },
  { 
    "startPath": "/path2", 
    "fixture": "fixture2"
  }
]

describe('Start test', function() {

  // Loop through both test
  states.forEach((state) => {

    // In this before statement the fixtures are setup
    before(function () {
      cy.flushDB()
      cy.fixture(state.fixture)
        .then(fixtureData => {
          new Cypress.Promise((resolve, reject) => 
            cy.createCollections(fixtureData, resolve, reject)
          )
        })
        .then(() => cy.visit(state.startPath)) 
    })
    
    context('Within this context', function() {
      it(`Can run some test for fixture ${state.fixture}`, function() {
        
      })
    })
  })
})

标签: javascriptcypress

解决方案


找到了一个解决方案:我不得不将它包装到另一个describe代码块中,然后它就起作用了:

const states = [
  { 
    "startPath": "/path1", 
    "fixture": "fixture1",
    "context": "1"
  },
  { 
    "startPath": "/path2", 
    "fixture": "fixture2",
    "context": "2"
  }
]

describe('Start test', function() {

  // Loop through both test
  states.forEach((state) => {

    // SOLUTION HERE
    describe(state.context, () => {
  
      // In this before statement the fixtures are setup
      before(function () {
        cy.flushDB()
        cy.fixture(state.fixture)
          .then(fixtureData => {
            new Cypress.Promise((resolve, reject) => 
              cy.createCollections(fixtureData, resolve, reject)
            )
          })
          .then(() => cy.visit(state.startPath)) 
      })
      
      context('Within this context', function() {
        it(`Can run some test for fixture ${state.fixture}`, function() {
          
        })
      })
    })
  })
})

推荐阅读