[英]Testing an Angular Promise with Jasmine
The following test keeps failing and I can't figure out why? 以下测试一直在失败,我无法弄清楚为什么? I am trying to figure out how to test defereds/promises with Jasmine.
我试图弄清楚如何用Jasmine测试defereds / promises。
Error 错误
Expected undefined to be 'Resolved Data'.
Test 测试
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');
});
});
Service 服务
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;
}
}
}]);
Try calling $timeout.flush()
before expect(result).toBe('Resolved Data');
尝试在
expect(result).toBe('Resolved Data');
之前调用$timeout.flush()
expect(result).toBe('Resolved Data');
. 。
In your example, you will need to call both $timeout.flush()
AND $rootScope.$apply()
. 在您的示例中,您需要同时调用
$timeout.flush()
和$rootScope.$apply()
。
Explanation: $timeout.flush()
will force your $timeout
in the service to run immediately. 说明:
$timeout.flush()
将强制服务中的$timeout
立即运行。 Your service will then call ' resolve
' - but the promise.then()
will not be called until the subsequent digest cycle; 然后你的服务将调用'
resolve
' - 但是在后续的摘要周期之前不会调用promise.then()
; therefore you will need to call $rootScope.$apply()
to propagate any 'resolves' and 'watches' - which will occur synchronously. 因此,您需要调用
$rootScope.$apply()
来传播任何'resolves'和'watches' - 这将同步发生。
NOTE:
In Jasmine, ensure that your promise.then()
function appears BEFORE
your call to $rootScope.$apply
otherwise it will not fire the promise.then()
function. NOTE:
在Jasmine中,确保BEFORE
调用$rootScope.$apply
BEFORE
出现promise.then()
函数$rootScope.$apply
否则它将不会触发promise.then()
函数。 (I haven't figured out why this is the case in Jasmine.) (我还没弄清楚为什么Jasmine会出现这种情况。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.