2013-02-08 63 views
3

所以我是新來angularjs和它的嘲笑庫。我想測試一個特定的GET請求,但我總是得到這個錯誤的斷言第二,不能找出原因:AngularJS問題嘲笑httpGET請求

Error: Unsatisfied requests: GET /1.json 

有什麼我搞砸了我下面的代碼?

App.js

var App = angular.module('App', []).config(['$routeProvider', function($routeProvider) { 
    $routeProvider.when('/', { 
    templateUrl: 'views/main.html', 
    controller: 'MainCtrl' 
    }).when('/Items', { 
    templateUrl: 'views/items.html', 
    controller: 'Ctrl' 
    }).otherwise({ 
    redirectTo: '/' 
    }); 
}]); 

Ctrl.js

function Ctrl($scope, $http, $filter) { 
    $scope.items = []; 

    $http.get('/1.json').success(function(data) {$scope.items = data.items;}); 
} 

Ctrl.$inject = ["$scope","$http", "$filter"]; 

規格/ Ctrl.js

describe('Controller: Ctrl', function() { 
    var $httpBackend; 
    // load the controller's module 
    beforeEach(module('App')); 
    beforeEach(inject(function($injector) { 
    $httpBackend = $injector.get('$httpBackend'); 

    // backend definition common for all tests 
    $httpBackend.whenGET('/1.json').respond('Response!'); 
    })); 

    afterEach(function() { 
    $httpBackend.verifyNoOutstandingExpectation(); 
    $httpBackend.verifyNoOutstandingRequest(); 
    }); 

    var Ctrl, scope; 

    // Initialize the controller and a mock scope 
    beforeEach(inject(function($rootScope, $controller) { 

    scope = $rootScope.$new(); 
    Ctrl = $controller('Ctrl', { 
     $scope: scope 
    }); 
    })); 

    it('should initialize with 0 items', function() { 
    expect(scope.items.length).toBe(0); 
    $httpBackend.flush(); 
    }); 

    it('should make store request', function(){ 
    var controller = scope.$new(Ctrl); 
    $httpBackend.expectGET('/1.json'); 
    $httpBackend.flush(); 
    }); 
}); 

EDIT:添加的應用程序和控制器的代碼。

+0

您的代碼表明您希望獲得「獲取」請求,但我沒有看到它在哪裏製作,這就是您遇到錯誤的原因。你在哪裏期待這個請求發生? –

+0

抱歉,我忘記了包含應用程序和控制器代碼。我已經這樣做了,是我的錯誤發生可能是由於routeProvider?我需要告訴我的測試以某種方式執行路線嗎? – Lucas

回答

4

我終於讓我的單元測試工作了!主要是因爲我重組了我的應用程序,使其更加合理,並且更加模塊化。

我會盡力提供信息以幫助運行到這個旁邊的人:

第一的是我轉向使用$資源,而不是$ HTTP。

,而不是注入$噴油器,我注入$ httpBackend像這樣:

beforeEach(inject(function(_$httpBackend_, $rootScope, $route, $controller){ 

    $httpBackend = _$httpBackend_; 
    $httpBackend.expectGET('/path/to/api').respond([{id:1}]); 

而不是引用 'Ctrl鍵' 作爲一個字符串,我在實際的類

Ctrl = $controller('Ctrl', { $scope: scope });

通過

變成

var ProductsCtrl = ['$scope', function($scope){ ... }]; 

Ctrl = $controller(ProductsCtrl, { 
    $scope: scope 
});` 

如果您使用$ resources,請確保您正在引用angular-resources.js文件

我真的很喜歡Angularjs;我想這只是需要一些時間來包裝你的頭如何測試。那裏好運!

+0

你可以看看這個嗎?我是新手,看起來和美國人很相似。 http://stackoverflow.com/questions/15981583/angular-js-how-to-mockor-stub-xhr-request-in-each-test – allenhwkim