简体   繁体   中英

Why does Mocha exit before a reporter is done handling a test failure?

I'm writing a test suite using PhantomJS (via selenium-webdriver ) and Mocha. For reporting I need a screenshot every time a test fails and so I've written a custom reporter for Mocha based on spec reporter:

module.exports = Screenshot;

var Spec = require('mocha/lib/reporters/spec');
var fs = require('fs');

// custom library generating 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 works');    

        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');    

    });
}

Screenshot.prototype.__proto__ = Spec.prototype;

Now I have a funny situation when a test fails: Mocha does everything synchronous from the hook callback (eg both logging statements), however neither the getCurrentUrl promise nor the one for takeScreenshot gets resolved, which is obviously not what I expected.

However, I've found out that if I throw an exception after those promises are defined (eg after driver.takeScreenshot() ), Mocha terminates immediately without either a proper report or an error message (OK so far, even though I'd prefer getting a "Reporter raised an unexpected exception" message), but resolves both WebDriver promises, so that a screenshot is taken and also the current URL is printed just before the exit.

I'm playing with a small test suite of a couple of tests only, so I assumed that maybe Mocha considers the hook done and returns to OS before promises have a chance to be resolved. Is there an another explanation? Am I at fault here or is it Mocha? How do I fix this properly?

PS: It's perfectly possible that selenium-webdriver and its promises framework is at fault here. However, I don't want to place blame, but find a solution and I'm happy about any explanation to this phenomenon.

Answering my own question: it seems Mocha is currently unable to work with async functionality in its hooks. I've opened an issue on Github about this.

Update: I've solved the problem and documented in the issue above. The problem was a wiki entry on Mocha, describing programmatical test run, which employed a straight process.exit() instead of async process.on("exit", ...) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM