私は単位テストをしたい非常に基本的な工場サービスを持っています。私は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