node.jsmocha.js

Getting the test name in the afterEach function in mocha


Let me start by saying I am quite new to node.js and mocha.It just breaks my head. I started using the tdd approach and I am trying to get the test that will start or has just finished from within the beforeEach and afterEach functions, but I've had no luck.(I am mostly interested in afterEach). At least I couldn't figure a neat way of doing it. The only thing I could think of was keeping the tests and the suite in a variable and then on afterEach() just do some matching to see which test has finished.

Ideally where it says 'test name' I want to have something like suite.test.name

suite('my test suite', function() {
    beforeEach(function () {
        console.log('test name');
    });
    test('first test', function (done) {
        var testarray = ['1', '3', '5', '7'];
        testarray.forEach(function(num, index) {
            console.log('num: ' + num + ' index: ' + index);
        }, 
        done());
    });
    afterEach(){
        console.log('test name');
    }
}

Solution

  • You get the name of the current test with this.currentTest.title

    afterEach(function(){
        console.log(this.currentTest.title)
    })