Categories
Automated Testing Mocha WebDriver

Accessing Mocha Test Metadata in Hooks

In setting up my WebDriverJs tests to run in Mocha I wanted to add some intelligent screenshot taking ability:

  1. Only take screenshots if the test has failed
  2. Include the name of the test in the screenshot file name to easily identify which test it relates to

Both of these involve accessing some metadata about a test in Mocha. Fortunately it’s easy to do:

test.afterEach(function() {
       if (this.currentTest.state == 'failed') {
           var prefix = this.currentTest.title.replace(/[^a-z0-9]/gi, '-').toLowerCase() + '-';
           driver.takeScreenshot().then(function (data) {
               mediaHelper.writeScreenshot(data, prefix);
           });
       }
});

The this.currentTest.state gives us the status of the test (eg. ‘failed’), and this.currentTest.title gives us the title of the lowest level mocha test running (you can use this.currentTest.fullTitle() to get the entire test chain).

One reply on “Accessing Mocha Test Metadata in Hooks”

Dude. Your blog is great. Every time I remember to check back, I see you’ve written another post that parallels the work I have been doing with my team. Thanks.

Leave a Reply

Your email address will not be published. Required fields are marked *