I'm trying to get the current describe
name inside the before
hook, like so:
describe('increasing 3 times', function() {
before(function() {
console.log('test name');
});
...
});
I basically want to retrieve the 'increasing 3 times' string in the before hook.
How can this be acplished?
Thanks!
I'm trying to get the current describe
name inside the before
hook, like so:
describe('increasing 3 times', function() {
before(function() {
console.log('test name');
});
...
});
I basically want to retrieve the 'increasing 3 times' string in the before hook.
How can this be acplished?
Thanks!
Share Improve this question asked Dec 18, 2014 at 18:51 Edy BourneEdy Bourne 6,20616 gold badges61 silver badges114 bronze badges 2- In case mocha doesn't provide an API for that, you could store the name in a variable. It won't read as nicely though. – Felix Kling Commented Dec 18, 2014 at 18:55
- True.. I'm trying to avoid that. – Edy Bourne Commented Dec 18, 2014 at 20:35
1 Answer
Reset to default 8Here's code that illustrates how you can do it:
describe("top", function () {
before(function () {
console.log("full title:", this.test.fullTitle());
console.log("parent title:", this.test.parent.title);
});
it("test 1", function () {});
});
Run with the spec
reporter, this will output:
full title: top "before all" hook
parent title: top
✓ test 1
1 passing (4ms)
When Mocha calls the functions you pass to its various functions (describe
, before
, it
, etc.) the value of this
is a Context
object. One of the fields of this object is named test
. It is a bit of a misnomer because it can point to something else than an actual test. In the case of a hook like before
it points to the current Hook
object created for the before
call. Calling fullTitle()
on this object will get you the hierarchical name of the object: the object's own name preceded by the name of the test suites (describe
) that enclose it. A Hook
object also has a parent
field that points to the suite that contains the hook. And the suite has a title
field which is the first argument that was passed to describe
.