Search code examples
node.jsprototypenightwatch.js

nightwatch custom command prototype


I followed the instruction from here (pause command in nightwatch), in order to create a custom command which gets the current used selector (css or xpath).

var util = require('util');
var events = require('events');

function GetSelector() {
    events.EventEmitter.call(this);
}

util.inherits(GetSelector, events.EventEmitter);

GetSelector.prototype.command = function (callback) {
    callback(this.client.locateStrategy);
};

module.exports = GetSelector;

The implementation gets the current selector, although the program stuck when the custom command is called.

  browser
    .getSelector(function (currentSelector) { 
      console.log('getSelector: ' + currentSelector); 
    })
    

I have also tried to wrap around with "self.perform" as suggested here, unfortunatelly without any luck.

GetSelector.prototype.command = function (browser, callback) {
    browser.perform(function () {
        callback(this.client.locateStrategy);
    })
};

What am I missing?


Solution

  • "Signaling the complete event needs to be done inside an asynchronous action" action"self.emit('complete');, according to the Nightwatch homepage.

    GetSelector.prototype.command = function (cb) {
        var self = this;
    
        process.nextTick(function () {
            cb(self.client.locateStrategy);
    
            //Signaling the complete event needs to be done inside an asynchronous action.
            self.emit('complete');
        });
    
        return this;
    };
    

    process.nextTick makes sure that the self.emit('complete'); will be called by the next tick of the event loop which are processed by Node.