Node Stub a method that returns an object

老子叫甜甜 提交于 2019-12-11 05:29:53

问题


I have a module that has some properties. I am using it as below

Var propmodule = require('me-props');
var prop = new propmodule('server');
prop.get('min); //returns 3
prop.get('max') //returns 10

I have to mock this for testing. Did the below code using proxyquire and sinon

var spro = proxyquire('../lib/add.js',{
'me-props' : sinon.stub.returns({
    get : sinon.stub.returns({
       min :'3',
       max : '10
)}
)}
})

The above code works. But while testing, the get method call returns an object. get(min) returns an object. var a = prop.get() and then a('min') returns 3. But prop.get('min') returns an object.

How can i modify the stub to return the value for the get call?


回答1:


One solution would be to predicate the returns with a withArgs so it will match the function arguments (min and max) and return a appropriate value:

var stub = sinon.stub();
stub.withArgs('min').returns('3');
stub.withArgs('max').returns('10');
stub.throws('InvalidArgument'); // Throw an exception when an invalid argument is used.

var spro = proxyquire('../lib/add.js', { 'me-props' : { get : stub } });


来源:https://stackoverflow.com/questions/38847398/node-stub-a-method-that-returns-an-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!