我正在尝试使用 chai、chai-as-promised、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 文档中描述的方法 sinon-as-promised 之前,我没有保留组件中使用的 Promise 来等待它。
我怎样才能通过这个测试?
最佳答案
您可以将来自 MyService.get
的 promise 存储为组件的属性:
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;
});
}
}
然后您将使用异步 Mocha 测试:
it("should load data upon activation", function (done) {
component.servicePromise.then(function() {
component.data.should.equal(5);
done();
});
});
关于javascript - 等待与 Mocha 未兑现的 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36675628/