0

I'm trying to test a JavaScript object with Mocha using chai, chai-as-promised, sinon, sinon-chai and sinon-as-promised (with Bluebird).

Here is the object under test:

function Component(MyService) {
  var model = this;
  model.data = 1;

  activate();

  function activate() {
    MyService.get(0).then(function (result) {
      model.data = result;
    });
  }
}

and here is the test:

describe("The object under test", function () {
  var MyService, component;

  beforeEach(function () {
    MyService = {
      get: sinon.stub()
    };
    MyService.get
      .withArgs(0)
      .resolves(5);
    var Component = require("path/to/component");
    component = new Component(MyService);
  });

  it("should load data upon activation", function () {
    component.data.should.equal(5); // But equals 1
  });
});

My problem is I don't have a hold on the promise used in the component to wait for it before checking with the ways described in the docs of Mocha, sinon-as-promised.

How can I make this test passing?

Mouz
  • 273
  • 2
  • 13

1 Answers1

1

You could store the promise from MyService.get as a property of the component:

function Component(MyService) {
  var model = this;
  model.data = 1;

  activate();

  function activate() {
    model.servicePromise = MyService.get(0);

    return model.servicePromise.then(function (result) {
      model.data = result;
    });
  }
}

Then you would use an async mocha test:

it("should load data upon activation", function (done) {
  component.servicePromise.then(function() {
       component.data.should.equal(5);
       done();
  });
});
vvondra
  • 3,022
  • 1
  • 21
  • 34
  • 1
    Although that would do the trick, I don't think it makes sense to have the promise as a property of the object just to be able to test it. – Mouz Apr 17 '16 at 13:08
  • You can then either poll and wait with timeout for success or have a different promise which would be more generic, something like componentReadyPromise, which you could attach your handler too – vvondra Apr 17 '16 at 20:45
  • Naming the property to something like activating can make sense. – Mouz Oct 30 '16 at 16:29