단위 테스트를하고자하는 매우 기본적인 공장 서비스가 있습니다. expect
문 앞에 $rootScope.$digest()
및 $rootScope.$apply()
을 시도했지만 단위 테스트에서 성공 또는 실패 처리기를 전혀 호출하지 않았습니다.하지만이 팩토리를 사용하는 컨트롤러의 컨텍스트에서 앱에서 정상적으로 호출됩니다.
example.service.js :
(function (angular) {
'use strict';
angular
.module('exampleModule')
.factory('ExampleApi', ExampleApi);
ExampleApi.$inject = ['$http'];
function ExampleApi($http) {
return {
get: getExampleData
}
function getExampleData() {
return $http.get('example-endpoint');
}
}
})(angular);
example.service.spec.js는
'use strict';
describe('Example API service', function() {
var $httpBackend;
var $rootScope;
var ExampleApi;
beforeEach(module('exampleModule'));
beforeEach(inject(
function(_$httpBackend_, _$rootScope_, _ExampleApi_) {
$httpBackend = _$httpBackend_;
$rootScope = _$rootScope_;
ExampleApi = _ExampleApi_;
}));
it('calls the success handler on success', function() {
$httpBackend
.expectGET('example-endpoint')
.respond(200);
var handlerStubs = {
success: function() {
console.log("success called");
},
failure: function() {
console.log("failure called");
}
}
spyOn(handlerStubs, 'success').and.callThrough();
spyOn(handlerStubs, 'failure').and.callThrough();
ExampleApi.get().then(handlerStubs.success, handlerStubs.failure);
//$rootScope.$digest();
$rootScope.$apply();
expect(handlerStubs.failure.calls.count()).toEqual(0);
expect(handlerStubs.success.calls.count()).toEqual(1);
});
});
,'시도'$ httpBackend.flush(); 그것은 바로 응답 (200)''후 작동하지만 그것을하지 않았다 @LukeHutton' –
'ExampleApi.get()'문장 다음에 DID. 이를 답으로 쓰면 올바른 것으로 표시하겠습니다. 고마워요! ('response'라인 다음에,'Error : 플러시 요청이 없다! '라고했기 때문에'get()'후에 시도해 보았습니다.) – anjunatl