I know how to use stub to replace one function.
sandbox.stub(Cars, "findOne",
() => {return car1 });
But now I have a line in my function I want to test that I need to stub that looks like this
Cars.find().fetch()
So there is a chain of function here and I'm unsure what I need to do. How do I stub "find" to return something that I can use to stub "fetch"?
This is another approach that also allows spying on chains of jQuery methods - which took me a long time to figure out.
In the example, I am trying to test that an email field is cleared out
and the function under test is (roughly):
The form of attaching a function to a stub shown here:
is deprecated.
It's now, as of version 6.3
IMHO, we can just use
returns
to do this. We don't need to usecallsFake
or mock it as function.in case, if there is another method after fetch(), we can use
returnsThis()
Ref: https://sinonjs.org/releases/v6.3.3/
Hope it helps
Try this:
I ran into this problem and, though I liked the solution for a single test, wanted something more dynamic that would allow for reuse across tests. I also preferred the sandbox approach, as it made restoring much easier for larger suites. End result:
Wherever I want to set up a stub on the fly, I pass in the created sandbox and the other parameters:
setupChainedMethodStub(sandbox, MyMongooseModel, 'findOne', ['sort', 'exec'], { foo: 'bar' })
Then I just have a
sandbox.restore()
in my highest scopedafterEach()