问题
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