Reputation: 11
I am trying to unit test method A. All the method does is call method B (which gets urlVars). If the result returned from method A to B is equal to the value passed in to method A then it must return true, else it returns false.
function A(result) {
if (B()["type"] === result) {
return true;
} else {
return false;
}
}
function B() {
do something
}
return something;
}
I am trying to make sure function B returns the same value I am passing into function A using sinon. Anyone that can help?
Upvotes: 1
Views: 1341
Reputation: 14845
The short answer is probably this:
// just for the example
var result = "test";
// function under test
function A(result) {
if (B()["type"] === result) {
return true;
} else {
return false;
}
}
//creating the stub
var B = sinon.stub()
// sets the return value of the Stub
B.returns({type:result});
// testing the function
console.info(A(result));
<script src="http://sinonjs.org/releases/sinon-1.17.5.js"></script>
The longer answer is check the documentation http://sinonjs.org/docs/#stubs . The question is do you really need sinonjs, or can you not handcode it?
By unit testing I would always handcode stubs/mocks/... first, and when I start coding to much or duplicating a lot I use a framework.
Update: some info to Unit testing
(I hope this is not too basic, and helps solve your issue)
If I'm testing the A
function, I want to know If the function A reacts how I imaging it. So I create testCases
TestCase 1) if I Call Function A
with the parameter test
the result should be true
.
TestCase 2) if I Call Function A
with the parameter test1
the result should be false
.
... and so on.
Problem: I just want to test the logic from A
, without calling B
and without relying on the functionality of B
Solution: I mock/stub/... it out.
Here how i would approach it (in a stackoverflow, environment)
var passed = "<span style='color:green'>passed</span><br />";
var failed = "<span style='color:red'>failed</span><br />";
// Helper UnitTesting framework ;-)
function assertIsEqulaHelper(expected, actual){
document.write(expected===actual?passed:failed);
}
var B;
function testCase1(){
B = sinon.stub();
B.onCall(0).returns({type:"test"});
assertIsEqulaHelper(true, A("test"));
}
function testCase2(){
B = sinon.stub();
B.onCall(0).returns({});
assertIsEqulaHelper(false, A("test1"));
}
// function under test
function A(result) {
if (B()["type"] === result) {
return true;
} else {
return false;
}
}
testCase1();
testCase2();
<script src="http://sinonjs.org/releases/sinon-1.17.5.js"></script>
This would have to be optimized, but it can work like this.
Final Update: Information integrated into provided Code
var expected = true;
var returnValue = "something";
var B = sinon.stub();
B.returns({type: returnValue});
//Act
var actual = A(returnValue); //use webm or local
//Assert
deepEqual(actual, expected);
Upvotes: 1