Search code examples
javascripttestingpromisesinonstub

Sinon How to stub Promise?


I have controller with following method that is invoked whenever new instance of a controller is created

initialize: function() {
    var self = this;
    return new View().render().then(function() {
        bus.broadcast("INITIALIZED");
    });
} 

I want to test this method:

it("should initialise controller", (done) => {
        bus.subscribe("INITIALIZED", (message, payload) => done());
        new Controller();
    });

How to stub Promise new View().render() with Sinon.JS to make this test work?


Solution

  • Based on information you've provided...:

    it("should initialise controller", (done) => {
        var renderStub = sinon.stub(View.prototype, 'render');
         // for each view.render() call, return resolved promise with `undefined`
         renderStub.returns(Promise.resolve());
    
        bus.subscribe("INITIALIZED", (message, payload) => done());
        new Controller();
    
        //make assertions...
    
        //restore stubbed methods to their original definitions
        renderStub.restore();
    });