在其中一项测试中出现错误的情况下仅中断当前测试用例的方法

时间:2019-08-31 20:59:48

标签: javascript mocha

我使用Mocha来使用puppeteer测试网站。我的测试用例中每个都有多个测试。

这里的问题是,如果任何测试失败,就没有意义进行进一步的测试。

describe('testset 1', function() {
  let browser
  let page

  before(async () => {
    browser = new Browser() //
    page = await browser.newPage()
    await page.goto('/testset1')
  })

  it('test first step', () => {
    // this action opens modal required for step 2
    await page.click('.first-step-button')
    // for some reason modal is not opened and test is failed
    expect(true).to.equal(false)
  })

  it('test second step', () => {
    // No sense to do this because this selector is inside modal
    page.click('.first-step-button')
  })
})


describe('testset 2', function() {
  let browser
  let page

  before(async () => {
    browser = new Browser() //
    page = await browser.newPage()
    await page.goto('/testset2')
  })

  it('test first step', () => {
    // this action opens modal required for step 2
    await page.click('.first-step-button')
    // for some reason modal is not opened and test is failed
    expect(true).to.equal(false)
  })

  it('test second step', () => {
    // No sense to do this because this selector is inside modal
    page.click('.first-step-button')
  })
})

我想在第一次测试出现错误后停止从testset 1运行测试,并切换到testset 2

有什么方法可以只破坏当前的测试集,以防内部测试出错?

我尝试了--bail mocha选项,但是它在出现第一个错误后立即停止测试,这是不希望的。即使我在描述部分中做同样的行为

describe('testset 1', function() {
  this.bail(true)
})

1 个答案:

答案 0 :(得分:0)

我为此目的的解决方法

afterEach(function() {
  // this is pointed to current Mocha Context
  const {currentTest} = this
  if (currentTest.state === 'failed') {
    // parent is pointed to test set which contains current test
    currentTest.parent.pending = true
  }
})

现在所有作品都能按预期

afterEach(function() {
  const {currentTest} = this
  if (currentTest.state === 'failed') {
    currentTest.parent.pending = true
  }
})

describe('testset 1', function() {
  it('test first step', () => {
    expect(true).to.equal(false)
  })

  it('test second step', () => {
    expect(true).to.equal(true)
  })
})

// this will be run after error in `testset 1`
describe('testset 2', function() {
  it('test first step', () => {
    // ...
  })

  // ...
})