Search code examples
javascripttestingnightwatch.js

What is the execution model for nightwatch custom commands, and how do I wait for them?


It appears that my custom commands implemented for Nightwatch.js are getting executed asynchronously. A console.log message inside the custom command is showing up after a console.log message issued from after the command is invoked. I can't find any reference in the nightwatch documentation about how these commands are executed, but since they appear to be asynchronous, I'm not sure how I can wait to make sure one command has completed before the next one is executed (because this doesn't not appear to be the case).

Here is my custom command ("foo"):

exports.command = function () {
    console.log('Command executed');
}

And my test function:

module.exports['my test'] = function(browser) {
    browser.resizeWindow(400, 600);
    browser.foo();
    console.log('Test function returning');
};

When I run this, the logs show up as:

Test function returning
Command executed

Which is the opposite order of what I would expect if my custom function was getting executed synchronously.


Solution

  • If you want your custom command to work properly (and be synch), you need to call at least one Nightwatch.js command inside your custom command.

    Try this:

    exports.command = function () {
        console.log('Command executed');
        this.execute(function() {});
    }
    

    If you want more in-depth details, you can follow this issue: https://github.com/nightwatchjs/nightwatch/issues/1123