Currently, I am developing a test suite using PhantomJS (via selenium-webdriver
) in conjunction with Mocha. In order to have screenshots generated whenever a test fails, I created a custom reporter for Mocha patterned after the spec
reporter:
module.exports = Screenshot;
var Spec = require('mocha/lib/reporters/spec');
var fs = require('fs');
// incorporating a customized library for managing PhantomJS instances
var phantoms = require("phantoms");
function Screenshot(runner) {
Spec.call(this, runner);
runner.on('fail', function(test, err){
var driver = phantoms.getDriver();
driver.getCurrentUrl().then(function(url) {
console.log(url);
});
console.log('This is functioning');
driver.takeScreenshot().then(function(img) {
console.log("Writing screenshot");
fs.writeFileSync("/tmp/selenium.png", img, 'base64');
return "/tmp/selenium.png";
});
console.log('This also works fine');
});
}
Screenshot.prototype.__proto__ = Spec.prototype;
Presently, there is an intriguing occurrence when a test fails: Mocha executes everything synchronously from the hook callback (including both logging statements). Nevertheless, neither the promises for getCurrentUrl
nor takeScreenshot
are resolved as anticipated.
Upon further exploration, it was discovered that throwing an exception post defining those promises (e.g. following driver.takeScreenshot()
) results in an immediate termination of Mocha without generating either a comprehensive report or an error message (this outcome is satisfactory; albeit ideally receiving a "Reporter raised an unexpected exception" notification), but does resolve both WebDriver promises. Consequently, a screenshot is captured and the current URL is printed just before exiting.
This experimentation pertains to a small-scale test suite consisting of only a handful of tests. One speculation is that Mocha perceives the hook as complete and returns control to the operating system prior to the opportunity for the promises to be fulfilled. Is there an alternative explanation? To whose fault can this issue be attributed - mine or Mocha's? What is the appropriate course of action for resolving this situation?
PS: It is conceivable that the blame lies with selenium-webdriver
and its promise framework in this instance. Nonetheless, rather than assigning responsibility, my objective is to identify a resolution. Any insight into this phenomenon would be greatly appreciated.