【问题标题】:nodejs module unit test method gets called in private classnodejs模块单元测试方法在私有类中被调用
【发布时间】:2014-02-16 03:11:37
【问题描述】:

我正在尝试对在我的模块中调用的方法进行单元测试。类和方法是私有的,不使用module.exports 公开。我用于测试的模块是:mocharewireassertsinon.spy。我要测试的调用是我的错误方法,这当前会引发错误,但以后可能会更改 - 所以我不想测试是否引发了错误,只需测试 class.error() 是否被调用。不知道如何继续,并在网上尝试了许多 tuts。

该类是(当前在使用rewire 的测试中访问):

var MyClass = function MyClass(o){

    var self = this

    if(!o || typeof o !== 'object')
        self.error('No configuration passed to MyClass')
}

MyClass.prototype.error = function(msg){

    throw Error(msg)
}

我目前的测试不起作用:

it('Constructs MyClass', function(done){

    //check constructs normally (this passes and works)
    var actual = obj.__get__("MyClass.config")
    assert.deepEqual(actual, config)

    /**
     * check calls error method
     */
    //stub class.error ?
    //construct class without config
    //check if class.error is called

    done()
})

在伪代码中,我希望做的是:

var stub = stub(MyClass)
    ->do('construct', null) //no config passed
    ->didCall('error') //check error method is called

这可能与以下内容重复:Mocking modules in Node.js for unit testing 但它给我一个错误:Object #<Object> has no method 'expect'

【问题讨论】:

    标签: node.js unit-testing mocking


    【解决方案1】:

    为了解决这个问题,我使用rewire 导入了私有类构造函数,然后我覆盖了错误方法,将其设置为sinon.spy。我构造了这个类,然后检查是否调用了间谍:

    //check calls error method if no config passed
    var obj = rewire('./path/to/my/module')
        , MyClass = obj.__get__("MyClass")
        , spy = sinon.spy()
    
    MyClass.prototype.error = spy
    var foo = new MyClass()
    assert.equal(spy.called, true)
    done()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多