首页 > 解决方案 > 在其中一项测试出错的情况下仅中断当前测试用例的方法

问题描述

我使用 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)
})

标签: javascriptmocha.js

解决方案


我为此目的的解决方法

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', () => {
    // ...
  })

  // ...
})

推荐阅读