下面的测试总是失败,我不知道为什么?我正在尝试找出如何使用Jasmine测试延迟/承诺。
错误
Expected undefined to be 'Resolved Data'.
测试
describe('Queued Repository', function () {
var ctrl,
rootScope,
scope,
service;
beforeEach(function () {
module('testApp');
inject(function ($rootScope, $controller, TestSrvc) {
rootScope = $rootScope;
scope = $rootScope.$new();
service = TestSrvc;
});
});
afterEach(inject(function ($rootScope) {
$rootScope.$apply();
}));
it('test something', function () {
expect(service.calculate(1, 5)).toBe(6);
});
it('resolves promises', function () {
var result;
service.getPromise().then(function (data) {
result = data;
});
rootScope.$apply();
expect(result).toBe('Resolved Data');
});
});
服务
var app = angular.module('testApp', []);
app.service('TestSrvc', ['$q', '$timeout', '$http', function ($q, $timeout, $http) {
return {
getPromise: function () {
var d = $q.defer();
$timeout(function () {
d.resolve('Defered Result');
}, 5000);
return d.promise;
},
getSomething: function () {
return "Test";
},
calculate: function (x, y) {
return x + y;
}
}
}]);
发布于 2013-10-31 23:51:32
尝试在expect(result).toBe('Resolved Data');
之前调用$timeout.flush()
。
发布于 2014-11-10 23:47:33
在您的示例中,您需要同时调用$timeout.flush()
和$rootScope.$apply()
。
说明:$timeout.flush()
会强制服务中的$timeout
立即运行。然后,您的服务将调用'resolve
‘--但直到随后的摘要周期才会调用promise.then()
;因此,您将需要调用$rootScope.$apply()
来传播任何'resolves’和'watches‘-这将同步发生。
NOTE:
在Jasmine中,确保您的promise.then()
函数出现在您对$rootScope.$apply
的调用中,否则它将不会触发promise.then()
函数。(我还没弄明白为什么Jasmine会这样。)
https://stackoverflow.com/questions/19718282
复制相似问题