Search code examples
javascriptunit-testingmocha.jssinonsinon-chai

How do I mock dependencies to return specific data?


Coming from Moq in C# where you can do the following:

someMock
    .Setup(toBeMocked => toBeMocked.MockedMethod(It.IsAny<Something>()))
    .Returns(something);

Then in the unit test when I call

toBeMocked.MockedMethod()

It returns something. How do I do this with sinonjs?


Solution

  • Sinon works a bit differently than Moq, largely because C# is a much different language than JS. Moq creates sub-classes to inject fake methods, while sinon is able to inject them by assigning them directly onto objects.

    Most basic pattern would be, assuming toBeMocked is an object with an instance method MockedMethod:

    sinon.stub(toBeMocked, 'MockedMethod').returns(something);
    

    This assigns the stub method to the MockedMethod property of the toBeMocked object. As such, it only affects that object, even if MockedMethod is a prototype method.

    If you want to replace a method for all instances of a constructor, you can do that instead. Assuming MockedClass is the constructor you used to create the toBeMocked object, it'd look like this:

    sinon.stub(MockedClass.prototype, 'MockedMethod').returns(something);
    

    Then later in your teardown code:

    MockedClass.prototype.MockedMethod.restore();
    

    You need to restore it like this because that prototype is not created anew between tests, so your stub will pollute your other test code if you don't.