4
我有我的組件裏面像這樣的代碼:測試抓承諾,AngularJS
p.a().then(function(x) {
vm.x = x;
return p.b();
}).then(function(y) {
if (!y) {
return $q.reject(new Error('My Error'));
}
vm.y = y;
return y;
}).catch(function(error) {
log.error(error);
});
我能夠測試的成功案例精:
it('is successful', function(done) {
spyOn(p, 'a').and.returnValue($q.resolve('x'));
spyOn(p, 'b').and.returnValue($q.resolve('y'));
$ctrl = $componentController('myComponent', {
$scope: $rootScope.$new()
});
p.a().then(function() {
expect($ctrl.x).toEqual('x');
return p.b();
}).then(function() {
expect($ctrl.y).toEqual('y');
done();
});
$timeout.flush();
});
但我不能測試catch
,並斷言錯誤:
it('fails', function(done) {
spyOn(p, 'a').and.returnValue($q.resolve());
spyOn(p, 'b').and.returnValue($q.resolve());
$ctrl = $componentController('myComponent', {
$scope: $rootScope.$new()
});
p.a().then(function() {
return p.b();
}).catch(function(error) {
expect(error).toEqual(new Error('My Error'));
done();
});
$timeout.flush();
});
所有當我運行測試中,我得到的是:
Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.
這意味着catch
甚至沒有運行(我試圖記錄一些東西來仔細檢查)。
任何想法我做錯了什麼?
我不知道你正試圖在這裏做。爲什麼大家還不你調用控制器'$ ctrl'上的任何函數嗎?你在測試什麼?測試中的代碼? – Sonata
@Sonata,你是什麼意思?我調用'p.a()'和'p.b()'都返回promise,解決後我在控制器中設置了一些數據,這就是我測試的'vm === $ ctrl' – jefujire