this.title prints out suite title, not test title
grvk opened this issue · 3 comments
Hi,
I'm trying to access title of the test case I'm currently with by running:
this.title
Unfortunately, I'm getting only Test Suite title.
Here is an example:
const forEach = require('mocha-each');
describe("TEMPORARY SUITE.", function() {
forEach( [0,1]).it("Test #%s", () => {
console.log(this.title);
});
});
Output:
TEMPORARY SUITE.
TEMPORARY SUITE.
✓ Test #0
TEMPORARY SUITE.
✓ Test #1
Okay, I found the root cause.
When we use arrow functions, not function statements in it() , the scope of this is very different.
Will mocha-each be supporting full functionality with arrow functions? Or is it completely under control of mochajs devs?
The reference of this in mocha-each's it() is same as Mocha's it() so you can use same helper methods like this.timeout in mocha-each unless you use arrow functions.
But it seems Mocha doesn't set this.title inside of it() blocks.
describe('suite title', function() {
console.log(this.title); // 'suite title'
it('test case title', function() {
console.log(this.title); // undefined
});
});However, we can access test case titles (and some other meta data) in beforeEach() and afterEach() instead of it() (mochajs/mocha#794).
describe('suite title', function() {
beforeEach(function() {
console.log(this.currentTest.title);
});
it('normal test', () => {});
forEach([0, 1]).it('test #%s', () => {});
});Output:
normal test
✓ normal test
test #0
✓ test #0
test #1
✓ test #1
I think this meets your requirement :)
Is there any way that we can get title of mocha tests in the same test.
describe("Login sample test",function()
{
console.log(this.title);
beforeEach( function()
{
console.log("beforeEach");
this.currentTest.title; //fails here, currentTest undefined
})
afterEach( function()
{
console.log("afterEach");
})
before( function()
{
console.log("before");
})
after( function()
{
console.log("after");
})
it("Login to Application",function(){
console.log("test");
console.log(this.title);
console.log(this.currentTest)
})
it("Login to Application2",function(){
console.log("test");
console.log(this.title); //fails here, title
console.log(this.currentTest) //fails here, currentTest undefined
})
})