What causes Mocha to exit prematurely before a reporter finishes handling a test failure?

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.

Answer №1

Just figured out the solution to my own question: it appears that Mocha is currently incompatible with async functions in its hooks. I've reported this issue on Github for further investigation, you can find it here.

Update: Good news - I managed to resolve the issue and have detailed the solution in the aforementioned Github post. Turns out, the problem stemmed from following a misleading wiki entry regarding Mocha's programmatic test run, which incorrectly utilized process.exit() instead of utilizing the proper async method process.on("exit", ...).

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

React Hooks: Unable to re-enable input after it has been disabled

Attempting to manage the status of my points input whether it's enabled or disabled, I encountered an issue. Upon checking the checkbox, it correctly gets disabled. However, upon unchecking it, the input remains disabled. Initially, I attempted settin ...

Icon not displaying in Firebase background service worker notifications with JavaScript

Although my firebase-messaging-sw.js is functioning properly in displaying background notifications, I have encountered an issue where the icon does not show up even though notification.title and notification.click_action are working correctly. Here is th ...

Show a variety of months using a datepicker arranged neatly in rows and columns

I need to display 13 months using multidatespicker. I achieved this with the following code: $(document).ready(function(){ $('#my_calendar').multiDatesPicker({ numberOfMonths: [4, 4], dateFormat: 'dd-mm-yy&a ...

Having issues with pageLoadTimeout function not functioning properly in Selenium framework

I have been trying to implement the following code using Selenium in Java. Even though I have set a pageLoadTimeout of 4 seconds, the driver still waits for the entire page to finish loading. Any suggestions on how to fix this? System.setProperty("webdr ...

What is the best way to navigate from one div to a particular slide within a slider?

Let's say I have two web pages: index.html and page.html. On page.html, there is a slider with 9 slides created using the plugin StackSlider. Now, when a link on index.html is clicked, I want to navigate to a specific slide, like slide number 4, on pa ...

Show the current date and time, and update it whenever the user chooses a different one

I need help with displaying the current date and time within a div, with the seconds refreshing when the page loads and changing when the user selects another date and time from the picker. I'm trying to accomplish this with the following script, but ...

Expandable Hover Navigation Bar with jQuery for Full Page Width Dimension

I currently have a vertical menu on my website and I am looking to implement a dropdown system for some of the links. I came across an example on the internet that inspired me: http://jsfiddle.net/4jxph/3018/ However, I specifically want a full-width subme ...

Tips for correctly loading all elements on an HTML page before making CSS modifications

This question has been asked several times in the past. I am asking because when I used the on ready callback in jQuery, it did not change the placeholder text of my element "search_input". $( document ).ready(function() { $("#search_input").attr(' ...

Assign an id attribute in KineticJS once the ajax call is successful

I have implemented KineticJS into my MVC application. To retrieve data from the database, I am utilizing ajax calls to web services in the API controller. One of the APIs returns an id that I want to assign to the current Kinetic.Group id attribute upon s ...

Is it possible for AngularJS custom filters to handle undefined arrays gracefully and still filter correctly?

I am currently working with an array of objects that are being assigned to the $scope within a controller. These objects are then filtered in multiple div elements within a partial template: <div class="entity-list"> <!-- Folders --> ...

JavaScript is unable to activate the button once it has been disabled

JS I am facing an issue with a form that has save and download buttons. I want the download button to be disabled initially, and then enabled once the form is saved. $("#download_form").attr('disabled', 'disabled'); $('.save ...

Sinon - observing the constructor function

While I've come across a few related inquiries, none seem to address what I am specifically looking to achieve. My goal is to monitor a constructor method in such a way that when an object created with the constructor calls this method from a differe ...

Encountering a ClassCast Exception for Actions.movetoElement with Selenium version 3.14.0+ post selenium upgrade

After updating selenium to the newest version 3.14.0, I encountered a class cast exception with the following method: new Actions(driver).moveToElement(element).click().build().perform(); The error message reads: java.lang.ClassCastException: com.prahs.u ...

Executing a JavaScript function using a batch file

After reading various posts on combining batch files and JavaScript, such as Embedded js in a batch file, I began to wonder if it is possible to use methods from a .js file in a .bat file. For example, let's define a js file with some methods: test.j ...

Automate the vertical resizing of a div element using code

Currently, I am utilizing Angular4+. I am looking to dynamically resize a div vertically, but I am unsure of how to go about it. I am uncertain about where to even begin and how to accomplish this task without resorting to using jQuery. Are there any sugg ...

The exceljs function for downloading an Excel workbook is not activated by using the Post method

Presently, I am engaged in the development of a React and Node application. This app is designed to store data entries in a database, with the capability for users to download all stored data in an Excel workbook. To make this possible, I have integrated ...

Tips for obtaining response headers

Currently, I am utilizing Angular version 15.0 and retrieving a list of items from the backend (ASP.NET Core 5) with an additional item attached to the header. The GET method in the client-side service is as follows: /** GET Paged commodities from the s ...

What can be done to prevent function from being treated as instance members within a controller's scope?

When using angularJS 1.3, the following code snippet showcases the functionality: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <script src="http ...

hashSync function needs both data and salt to generate the hash

I can't figure out why I am encountering this issue, I have checked the documentation and couldn't find my mistake. Any suggestions? Error: data and salt arguments required const {create} = require('./user.service'); const {genSaltS ...

Steps to confirm a particular element on a separate page within the login module

In my web application, there is a scenario where the user logs in for the first time and sees their username on the main page (implemented using a data-driven approach with @factory). However, if the user logs out and then logs in again, a new page display ...