Skip to content
Advertisement

How to create it test name with increment variable in Mocha

I am using Mocha and I would like to do something like this:

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')
})
})  

I get Test undefined as a test name, instead of Test 1, Test2. How can I achieve this in Mocha?

Advertisement

Answer

Due to how hooks works, you can use an increment into the name like this.

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

And you get the output:

  My tests        
inside first test 
    √ Test 1      
inside second test
    √ Test 2   
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement