0
這裏是我的代碼部分:單元測試數據從服務抵達控制器(茉莉花)
angular.module('mine',[]).factory('MyFactory', ['$http','$q', function
MyFactory($http,$q) {
return {
getData: function() {
var deferred = $q.defer(),
url = "http://...";
$http.jsonp(url)
.then(
function (response) {
deferred.resolve(response.data);
},
function (error) {
return $q.reject('Error retrieving data');
}
);
return deferred.promise;
}
};
}]);
function MyController(MyFactory) {
var self = this;
self.getData= function() {
MyFactory.getData().then(
function(result) {
self.contacts = result;
},
function(error) {
console.log('Error retrieving data: ', error);
}
);
};
self.getData();
}
angular.module('mine').component('myComponent', {
templateUrl: '..',
controller: MyController
});
我試圖單元測試,如果從工廠的數據正確地去控制器。以下是我使用Jasmine的單元測試代碼:
describe('component',() => {
let $componentController,contactsList,ctrl,$q,$rootScope;
beforeEach(angular.mock.module('mine'));
beforeEach(inject((_$componentController_,_MyFactory_, _$q_, _$rootScope_) => {
$componentController = _$componentController_;
ctrl = $componentController('myComponent',null);
$q = _$q_;
contactsList = _MyFactory_;
$rootScope = _$rootScope_;
}));
it('should ... ', function() {
spyOn(contactsList, "getData").and.returnValue(
$q.when({
message: 'awesome message'
}));
ctrl.getData();
$rootScope.$apply();
expect(ctrl.contacts.message).toBe('awesome message');
});
});
由於某些原因,上述測試未運行;我收到以下錯誤:Possibly unhandled rejection: Error retrieving data thrown
。你有什麼想法,爲什麼?哪裏不對?