首页 > 解决方案 > 如何在 Mocha 中使用增量变量创建测试名称

问题描述

我正在使用 Mocha,我想做这样的事情:

describe('My tests', () => {
let i
before(function () {
    i = 0
})
beforeEach(function () {
    i++
})

it('Test ' + i, function () {
    cy.log('inside first test')
})

it('Test ' + i, function () {
    cy.log('inside second test')
})
})  

我得到Test undefined一个测试名称,而不是Test 1, Test2。我怎样才能在摩卡中实现这一点?

标签: javascriptmocha.js

解决方案


由于钩子的工作方式,您可以像这样在名称中使用增量。

describe('My tests', () => {
    let i = 0
    it('Test ' + ++i, function () {
        console.log('inside first test')
    })
    
    it('Test ' + ++i, function () {
        console.log('inside second test')
    })
})

你得到输出:

  My tests        
inside first test 
    √ Test 1      
inside second test
    √ Test 2   

推荐阅读