let's say i have a function
Func a() {
//Do Something
let c = b();
return c;
}
I want to test the function a and mock b() and in the mock want to assign c. Sinon.Stub(Test,"b").returns("DummyValue"); c should be assigned DummyValue.
How can I do that?
describe("a", () => {
let a = a();
//mock b();
action = execute(a);
expect(action).should.return.("DummyValue");
})
You can stub function only
sinon
import
orrequire
). In such case you can useproxyquire
to pass in your fakeb
function for module under test. Function itself can be faked bysinon
or other test doubles library.When we have 2 functions in the same file and want to stub one of them and test the other. For example,: Test: tests.js
Dev: foo.js
We cannot do that, because after compilation the functions are exported with different signatures, with full name and while stubbing we stub the global function but while calling it from within the other function, we call the local function, hence it doesn’t work. There is a workaround to do that.
test.js
Ref: Stubbing method in same file using Sinon
In this case a sinon stub is more appropriate then a mock When to use mocks vs stubs?
Our assertion in the test is not on a specific call of function a i.e 1st or 3rd call but on all calls.
We can tel this because we have programmed our stub to always return the same result regardless of the way in which it is being called (arguments, or number of calls).
Pass a sinon stub function as an argument to function a.
test.js
Note that we can use const for these variable declarations as they are never being reassigned.