16
對於我的生活,我無法獲得$ httpBackend來處理執行$ http get請求的控制器。我已經嘗試了幾個小時,現在=)
我已經減少到最簡單的形式,我可以在下面。該測試通過,如果我
- 註釋掉控制器
- 註釋掉「httpMock.flush()」中考
- 而變「豬」和$ http.get()請求「狗「來匹配
也就是說,它是一個有效的工作測試和應用程序。
如果我把它放回去,我會看到底部顯示的錯誤。
應用程序/ JS/app.js
// Declare a module which depends on filters and services.
var myApp = angular
.module('myApp', ['ngRoute', 'myApp.filters', 'myApp.services',
'myApp.directives'])
.config(['$routeProvider' , function($routeProvider) {
$routeProvider
.when("/dashboard", {
templateUrl: "partials/dashboard.html",
controller: cDashboard
})
.otherwise({redirectTo: "/dashboard"});
}]);
// Pre-define our main namespace modules.
angular.module('myApp.directives' , []);
angular.module('myApp.filters' , []);
angular.module('myApp.services' , []);
angular.module('myApp.controllers', []);
應用程序/ JS/controller.js
function cDashboard ($scope, $http) {
$scope.data = "dog";
// Fetch the actual data.
$http.get("/data")
.success(function (data) { $scope.data = data })
.error(function() {});
}
cDashboard.$inject = [ '$scope', '$http' ];
測試/單元/ controllerSpec.js
describe('cDashboard', function(){
var scope, ctrl, httpMock;
beforeEach(inject(function ($rootScope, $controller, $http, $httpBackend) {
scope = $rootScope.$new();
ctrl = $controller('cDashboard', {$scope: scope});
httpMock = $httpBackend;
httpMock.when("GET", "/data").respond("pig");
}));
it("should get 'pig' from '/data'", function() {
httpMock.expectGET("/data").respond("pig");
expect(scope.data).toBe("pig");
});
});
這是我在shell得到錯誤:
INFO [watcher]: Changed file "/home/myApp/test/unit/controller/cDashboard.js".
Chrome 26.0 (Linux) cDashboard should get 'pig' from '/data' FAILED
Error: No pending request to flush !
at Error (<anonymous>)
at Function.$httpBackend.flush (/home/myApp/test/lib/angular/angular-mocks.js:1171:34)
at null.<anonymous> (/home/myApp/test/unit/controller/cDashboard.js:15:18)
Chrome 26.0 (Linux): Executed 1 of 1 (1 FAILED) (0.326 secs/0.008 secs)
謝謝!在實例化控制器之前,plunk和.expectGET必須發生的解釋非常有幫助。 – 2013-05-08 14:01:54