How to stub the return value on a mocked method in SinonJS

18,504

In the official docs http://sinonjs.org/docs/#stubs

var stub = sinon.stub(object, "method", func);

You could pass a function argument that returns your desired value.

EDIT:

This has been removed from v3.0.0. Instead you should use

stub(obj, 'meth').callsFake(fn)
Share:
18,504
josiah
Author by

josiah

During my day job, and even sometimes in my hobbies, I am a programmer and software engineer. Within the software engineering realm, I'm most interested in design patterns, techniques, theories, and language features that make software systems easiest to develop, maintain, and support. My key interest of late is strongly typed functional languages (such as Haskell and Scala) for all the benefits they seem to provide the developer without causing much of a performance hit. I work in the nitty-gritty often in my day job, but my preference is to understand things well at the most general and abstract levels of programming to apply solutions more broadly. Outside of software, I have varied interests. The chief among them is Eastern Orthodox Christianity, so you will find me fairly active on the Christianity SE site. However, I also have interests in creative writing (poetry in particular), personal finance (who doesn't?), food, travel, philosophy, and the outdoors (especially rock climbing).

Updated on June 29, 2022

Comments

  • josiah
    josiah almost 2 years

    I want to do something like the following:

    sinon.mock(obj)
    .expects('func')
    .atLeast(1)
    .withArgs(args)
    .returns(somePredefinedReturnValue);
    

    Where I expect everything up to and including withArgs, but then I need to stub the return value of the method so that when it returns it doesn't break the rest of the execution flow within the method under test.

    The reason I'm doing this is because I found out that some of my REST endpoint tests will silently pass when they should really be failing if a stubbed method with a callback that has an assertion inside of it doesn't get called. I'm trying to verify that these callbacks are actually getting called so that my tests don't give false positives.