Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock a function inside another function (which I am testing) using sinon?

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");
})
like image 939
Ravi Shankar Avatar asked Feb 09 '17 11:02

Ravi Shankar


People also ask

How do you mock a function in Sinon?

Mocks allow you to create a fake function that passes or fails depending on your needs. You can ensure it was called with certain arguments, or check how many times it was called. You must call mock() on an object.

How do I stub an object in Sinon?

If you need to check that a certain value is set before a function is called, you can use the third parameter of stub to insert an assertion into the stub: var object = { }; var expectedValue = 'something'; var func = sinon. stub(example, 'func', function() { assert. equal(object.

What is Sinon Spy ()?

Creates an anonymous function that records arguments, this value, exceptions and return values for all calls. var spy = sinon. spy(myFunc); Wraps the function in a spy. You can pass this spy where the original function would otherwise be passed when you need to verify how the function is being used.

How do you stub a promise in Sinon?

To stub a promise with sinon and JavaScript, we can return a promise with a stub. import sinon from "sinon"; const sandbox = sinon. sandbox. create(); const promiseResolved = () => sandbox.


1 Answers

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

let ComputeSumStub = sinon.stub(OfflineLoader, "ComputeSum");
const ans = function ()
{
    return 10;
};
ComputeSumStub.returns(ans);
const actualValue: number = OfflineLoader.sum();
expect(actualValue).to.be.equal(10);

Dev: foo.js

function sum(): number
{
    return ComputeSum(8, 9);
}

function ComputeSum(a: number, b: number): number
{
    return a + b;
}

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.

foo.js
const factory = {
  a,
  b,
}
function a() {
  return 2;
}

function b() {
  return factory.a();
}

module.exports = factory;

test.js

const ser = require('./foo');
const sinon = require('sinon');

const aStub = sinon.stub(ser, 'a').returns('mocked return');
console.log(ser.b());
console.log(aStub.callCount);

Ref: Stubbing method in same file using Sinon

like image 124
Ravi Shankar Avatar answered Sep 17 '22 14:09

Ravi Shankar