Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Mocha test name in the "before" hook?

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!

like image 881
Edy Bourne Avatar asked Dec 18 '14 18:12

Edy Bourne


People also ask

How do I run a specific test case in Mocha?

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.

Does Mocha run tests in order?

Usage. Your tests will run in the given order.

How do you test for Mocha and chai tea?

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.

How do you use a Mocha Beforeall?

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() .


1 Answers

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.

like image 197
Louis Avatar answered Oct 04 '22 17:10

Louis