Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using SinonJS stub (with rewire)

I have a function:

var publish = function(a, b, c) {
    main = a + getWriterName(b,c);
}

and getWriterName is another function:

var getWriterName = function(b,c) {
    return 'Hello World';
}

I want to test the "publish" function but I do not want to run the "getWriterName" function while I am testing "publish". I feel like I stub getWriterName function because I don't want to run it everytime I test "publish", but how do I do that? I did something like:

var sandbox = sinon.sandbox.create();
sandbox.stub(getWriterName).returns('done');

But this gives me an error of

TypeError: Attempted to wrap undefined property undefined as function

What is wrong with my stubbing if I am in the write path?

Edit: I am using rewire so would like solutions using rewire

like image 741
Samman Bikram Thapa Avatar asked Dec 25 '22 03:12

Samman Bikram Thapa


1 Answers

This is how Sinon can be used with Rewire to stub a function. Rewire in this case is particularly useful if the stubbed function is private.

it('getWriteName always returns "Hello World"', function() {      
    var stub = sandbox.stub();
    stub.returns('Hello World');
    var unset = log.__set__('getWriterName', stub);

    // your test and expectations here

    unset();
    // it's always good to restore the previous state
});
like image 129
Stéphane Bruckert Avatar answered Dec 26 '22 19:12

Stéphane Bruckert