Sinon.js和测试事件和新的

时间:2013-11-12 12:15:10

标签: node.js events testing sinon

我正在尝试模拟node.js应用程序,但它无法按预期工作。

我有一个名为GpioPlugin的node.js模块,其方法如下:

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;
}

现在我想用sinon为这个方法编写一个测试,但我不知道怎样...测试这个的最佳方法是什么?

如果测试结果,这个树部分会很好: 错误(没问题) 生成onOff(如何?) 具有正确参数的事件

1 个答案:

答案 0 :(得分:0)

如果还没有,那么您将要将onOff放入模块中,以便您的测试可以注入存根。

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的内容。