nodejs模块单元测试方法在私有类中调用

时间:2014-02-15 11:11:10

标签: node.js unit-testing mocking

我正在尝试单元测试在我的模块中调用方法。该类和方法是私有的,不使用module.exports公开。我用于测试的模块是:mocharewireassertsinon.spy。我想要测试的调用是我的错误方法,这当前抛出一个错误,但可能会在以后更改 - 所以我不想测试是否抛出了错误,只是测试class.error()被调用。不确定如何处理并尝试在线尝试多次。

该类是(目前在使用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'

1 个答案:

答案 0 :(得分:0)

要解决这个问题,我使用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()