我试图测试一个服务,我使用Angular的$q实现Promise。我将Karma,Mocha,Chai,Sinon,Sinon Chai和Chai视为承诺。
我编写并返回的所有测试都通过了,但拒绝或使用$q.all([ ... ])
的测试通过。我尝试了所有我能想到的,但我似乎无法找到问题所在。
以下是我所测试的缩小版本:
"use strict";
describe("Promise", function() {
var $rootScope,
$scope,
$q;
beforeEach(angular.mock.inject(function (_$rootScope_, _$q_) {
$rootScope = _$rootScope_;
$q = _$q_;
$scope = $rootScope.$new();
}));
afterEach(function() {
$scope.$apply();
});
it("should resolve promise and eventually return", function() {
var defer = $q.defer();
defer.resolve("incredible, this doesn't work at all");
return defer.promise.should.eventually.deep.equal("incredible, this doesn't work at all");
});
it("should resolve promises as expected", function() {
var fst = $q.defer(),
snd = $q.defer();
fst
.promise
.then(function (value) {
value.should.eql("phew, this works");
});
snd
.promise
.then(function (value) {
value.should.eql("wow, this works as well");
});
fst.resolve("phew, this works");
snd.resolve("wow, this works as well");
var all = $q.all([
fst.promise,
snd.promise
]);
return all.should.be.fullfiled;
});
it("should reject promise and eventually return", function() {
return $q.reject("no way, this doesn't work either?").should.eventually.deep.equal("no way, this doesn't work either?");
});
it("should reject promises as expected", function() {
var promise = $q.reject("sadly I failed for some stupid reason");
promise
["catch"](function (reason) {
reason.should.eql("sadly I failed for some stupid reason");
});
var all = $q.all([
promise
]);
return all.should.be.rejected;
});
});
第三,最后和第一个测试是失败的。其实它不会失败,它只是在超时超时后解决,我得到一个Error: timeout of 2000ms exceeded
。
编辑:我刚刚试过用Kris Kowal的承诺实施测试,它工作得很好。
P.S.我实际上发现在摩卡,柴或Chai As Promised的碗中有一段时间,并且afterEach
挂钩被调用的时间晚于超时。
如果我理解伪代码,它看起来好像你没有调用'$ scope。$ apply()',直到你发布了期望值。你能否在你解决/拒绝承诺后尝试调用它? – 2014-11-07 22:22:43
我实际上已经尝试过了,我会尽快完成这些测试。 – Roland 2014-11-08 10:02:13
运行'$ scope。$ apply()'在afterEach'中可能会成为一个问题,如果你期望在afterEach运行之前承诺的价值 – 2014-11-09 03:41:04