hongkong
hongkong

Reputation: 55

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?

Upvotes: 1

Views: 5943

Answers (2)

y4h2
y4h2

Reputation: 3383

With Sinon v2.3.1, you can do it as following.

const sinon = require('sinon');
let sandbox;
beforeEach('create sinon sandbox', () => {
  sandbox = sinon.sandbox.create();
});

afterEach('restore the sandbox', () => {
  sandbox.restore();
});

it('should initialize controller', (done) => {
  sandbox.stub(View.prototype, 'render').resolves();

  bus.subscribe("INITIALIZED", (message, payload) => done());
  new Controller();
});

Upvotes: 1

user2694295
user2694295

Reputation: 390

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();
});

Upvotes: 4

Related Questions