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 accomplished?
Thanks!
The exclusivity feature allows you to run only the specified suite or test-case by appending .only() to the function. Here's an example of executing only a particular suite: describe('Array', function () { describe.only('#indexOf()', function () { // ... }); }); Note: All nested suites will still be executed.
Usage. Your tests will run in the given order.
Introduction to Unit Testing with Mocha and ChaiIt supports asynchronous testing running the tests serially, allowing for more flexible and accurate reporting. It is a highly customizable framework that supports different assertions and libraries. Chai is an assertion library that is mostly used alongside Mocha.
before(function() {}) runs before all tests in the block. beforeEach(function() {}) runs before each test in the block. If you want to run a singular function at the start of your tests, use before() . If you want to run a function before each of your tests, use beforeEach() .
Here'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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With