Sinon.js and testing with events and new

I am trying to make fun of a node.js application, but it does not work properly.

I have a node.js module called GpioPlugin with the following method:

function listenEvents(eventId, opts) {
   if(!opts.pin) {
      throw new Error("option 'pin' is missing");
   }
   var listenPort = new onOff(opts.pin, 'in', 'both', {persistentWatch: true});

   listenPort.watch(function(err, value) {
      process.emit(eventId+'', value);
   });
}
if(typeof exports !== 'undefined') {
    exports.listenEvents = listenEvents;
}

and now I want to write a test using synon for this method, but I don’t know how ... What would be the best way to test this?

These parts of the tree would be perfect if they were checked: Error (no problem) onOff generation (how?) Event with the correct parameters

+4
source share
1 answer

If this is not the case, you will want to add onOffto the module so that your test can enter a stub.

var sinon = require("sinon");
var process = require("process");
var onOffModule = require(PATH_TO_ONOFF);  //See note
var gpio = require(PATH_TO_GPIO);

var onOffStub;
var fakeListenPort;

beforeEach(function () {
    //Stub the process.emit method
    sinon.stub(process, "emit");

    //Constructor for a mock object to be returned by calls to our stubbed onOff function
    fakeListenPort = {
        this.watch = function(callback) {
            this.callback = callback; //Expose the callback passed into the watch function
        };
    };

    //Create stub for our onOff;
    onOffStub = sinon.stub(onOffModule, "onOff", function () {
        return fakeListenPort;
    });
});

//Omitted restoring the stubs after each test

describe('the GpioPlugin module', function () {
    it('example test', function () {
        gpio.listenEvents("evtId", OPTS);

        assert(onOffStub.callCount === 1); //Make sure the stub was called
        //You can check that it was called with proper arguments here

        fakeListenPort.callback(null, "Value"); //Trigger the callback passed to listenPort.watch

        assert(process.emit.calledWith("evtId", "Value")); //Check that process.emit was called with the right values
    });
});

. onOff , .

, onOff , , , onOff. , , , , - proxyquire.

0

All Articles