4

我正在尝试模拟 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 编写一个测试,但我不知道如何......测试这个的最佳方法是什么?

如果经过测试,此树部分会很好: Error (no problem) generation of onOff (how?) event with correct params

4

1 回答 1

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的东西。

于 2014-05-20T02:13:07.493 回答