我正在尝试使用chai,chai-promise,sinon,sinon-chai和sinon-as-promised(使用Bluebird)在Mocha中测试JavaScript对象。
这是被测试的对象:
function Component(MyService) {
var model = this;
model.data = 1;
activate();
function activate() {
MyService.get(0).then(function (result) {
model.data = result;
});
}
}
这是测试:
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
});
});
我的问题是,在检查Mocha的文档中所描述的方式之前,我没有把握组件中使用的promise的承诺。
我如何才能通过此测试?
您可以将promiseMyService.get
作为组件的属性存储:
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;
});
}
}
然后,您将使用异步摩卡测试:
it("should load data upon activation", function (done) {
component.servicePromise.then(function() {
component.data.should.equal(5);
done();
});
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句