angular js単体テストで、beforeEachメソッドではなく、各テスト(「it」メソッド内)にxhr応答を設定したかったのですが、機能していないようです。
これは機能します
describe('ExampleListCtrl', function(){
var $scope, $httpBackend;
beforeEach(inject(function(_$httpBackend_, $rootScope, $controller) {
$httpBackend = _$httpBackend_;
$httpBackend.expectGET('examples').respond([]); // <--- THIS ONE
$controller(ExampleListCtrl, {$scope: $scope = $rootScope.$new()});
}));
it('should create "examples" with 0 example fetched', function() {
expect($scope.examples).toBeUndefined();
$httpBackend.flush();
expect($scope.examples).toEqual([]);
});
});
結果
Executed 8 of 8 SUCCESS (0.366 secs / 0.043 secs)
しかし、expectGetメソッドを各メソッドに移動すると、これはエラーで失敗します。どうしてか分かりません。
describe('ExampleListCtrl', function(){
var $scope, $httpBackend;
beforeEach(inject(function(_$httpBackend_, $rootScope, $controller) {
$httpBackend = _$httpBackend_;
$controller(ExampleListCtrl, {$scope: $scope = $rootScope.$new()});
}));
it('should create "examples" with 0 example fetched', function() {
$httpBackend.expectGET('examples').respond([]); // <--- MOVED TO HERE
expect($scope.examples).toBeUndefined();
$httpBackend.flush();
expect($scope.examples).toEqual([]);
});
});
ここにエラーがあります
....
at /Users/me/app/test/unit/controllers/ExampleListCtrlSpec.js:3:1
Error: No pending request to flush
at Error (<anonymous>)
at Function.$httpBackend.flush (/Users/me/app/test/lib/angular/angular-mocks.js:1171:34)
at null.<anonymous> (/Users/me/app/test/unit/controllers/ExampleListCtrlSpec.js:14:18)
---- 編集済み ----
以下のアドバイスに従って、コントローラーを beforeEach から移動し、テストを次のように変更して、$httpBackend.expectGET を複数回テストできるようにしました。
describe('ExampleListCtrl', function(){
var $scope, $rootScope, $httpBackend;
beforeEach(inject(function(_$httpBackend_, $rootScope, $controller) {
$httpBackend = _$httpBackend_;
controller = $controller;
$scope = $rootScope.$new();
}));
it('should create "examples" model with 0 example fetched from xhr', function() {
$httpBackend.expectGET('examples').respond([]);
controller(ExampleListCtrl, {$scope: $scope});
$httpBackend.flush();
expect($scope.examples).toEqual([]);
});
});