我試圖測試一個服務,我使用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