【问题标题】:Sinon.js and testing with events and newSinon.js 和使用事件和新的测试
【发布时间】:2013-11-12 12:15:09
【问题描述】:

我正在尝试模拟 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 的生成(如何?) 具有正确参数的事件

【问题讨论】:

  • onOff 是从哪里来的,是在模块中定义的吗?需要像onOff = require('./onOff')?或者喜欢onOff.require('./foo').onOff

标签: node.js events testing sinon


【解决方案1】:

如果还没有,您需要将 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 之类的内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-26
    • 1970-01-01
    • 2014-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多