最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Sinon How to stub Promise? - Stack Overflow

programmeradmin1浏览0评论

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?

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?

Share Improve this question asked Jan 16, 2017 at 20:11 hongkonghongkong 551 silver badge6 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

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

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();
});
发布评论

评论列表(0)

  1. 暂无评论