In setting up my WebDriverJs tests to run in Mocha I wanted to add some intelligent screenshot taking ability:
- Only take screenshots if the test has failed
- 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).