w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Event is not catched in my test with stubbed function

Your stub changed the sync/async aspect of process.exec().

The internal Node's implementation guarantees that the callback is always run in the next turn of an event loop:

myEvent = new Event(); // calls process.exec
myEvent.on('test', function() {
    expect(exec.cmd).to.equal('ls -l');
    done();
});
// process.exec callback will be called after all this code is executed

Your stub is calling the callback immediately:

myEvent = new Event(); // calls process.exec
// process.exec callback is called immediately
// test event is emitted before listeners are attached
myEvent.on('test', function() {
  expect(exec.cmd).to.equal('ls -l');
  done();
});

The solution is process.nextTick():

var execStub = function() {
  var _self = this;
  return sinon.stub(proc, 'exec', function(cmd, callback) {
      _self.cmd = cmd;
      console.log(cmd);
      process.nextTick(callback);
  });
};

Your test has another problem: _self in the exec stub callback is referring to the global object, you are saving the value to global.cmd. You are expecting to have the value in exec.cmd in the test later.

Here is the final & fixed version of execStub:

var execStub = function() {
    var _self = sinon.stub(proc, 'exec', function(cmd, callback) {
        _self.cmd = cmd;
        console.log(cmd);
        process.nextTick(callback);
    });
    return _self;
};

See this post for more information on callback asynchronicity.





© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.