2013-07-28 69 views
1

下面是我的茉莉花RoutesSpec.js單元測試AngularJS路線投擲錯誤:意外請求

describe("Todo Routes", function(){ 
    var route; 
    var rootScope; 
    var location; 

    beforeEach(function(){ 
     module('todoApp'); 

     inject(function($route, $location, $rootScope){ 
      route = $route; 
      location = $location; 
      rootScope = $rootScope; 
     }); 
    }); 

    it("should navigate to todo list", function(){ 
     expect(route.current).toBeUndefined(); 
     location.path('/todos'); 
     rootScope.$digest(); 
     expect(route.current.templateUrl).toBe('app/html/listTodos.html'); 
    }); 
}); 

下面是我的app.js

var todoModule = angular.module("todoApp", []); 

todoModule.config(function($routeProvider){ 
    $routeProvider.when('/todos', { 
     templateUrl: '../html/listTodos.html', 
     controller: 'TodoListController' 
    }) 
    .otherwise({redirectTo: '/todos'}); 
}); 

todoModule.controller("TodoListController", function($scope, $log){ 
    $scope.todos = [{title: "My first task", done: false}]; 
    $log.log('In list controller'); 
}); 

執行該規範拋出我下面的錯誤:

Error: Unexpected request: GET ../html/listTodos.html No more request expected at Error() at $httpBackend (C:/Learn/Javascript/todo_app/libs/angular-mocks.js:934:9) at sendReq (C:/Learn/Javascript/todo_app/libs/angular.js:9146:9) at $http (C:/Learn/Javascript/todo_app/libs/angular.js:8937:17) at Function.$http.(anonymous function) (C:/Learn/Javascript/todo_app/libs/angular.js:9080:18) at $q.when.then.then.next.locals (C:/Learn/Javascript/todo_app/libs/angular.js:7440:34) at wrappedCallback (C:/Learn/Javascript/todo_app/libs/angular.js:6846:59) at wrappedCallback (C:/Learn/Javascript/todo_app/libs/angular.js:6846:59) at C:/Learn/Javascript/todo_app/libs/angular.js:6883:26 at Object.Scope.$eval (C:/Learn/Javascript/todo_app/libs/angular.js:8057:28)

+0

根設置爲/待辦事項在您的測試引發的HTTP負載與此路線相關的部分。但既然你沒有嘲笑httpBackend來告訴它在接收到這個部分的請求時該怎麼做,你會得到這個錯誤。 –

+0

這是否意味着,Juho提供的解決方案在這裏http://stackoverflow.com/questions/15990102/angularjs-route-unit-testing也不起作用? – Ajay

+0

不知道。不是角度的專家。我只是分析你得到的錯誤。 –

回答

2

這意味着有一個AJAX調用來獲取模板。 $ httpBackend.expectGET( '應用程序/ HTML/listTodos.html')響應(200)可以調用路徑()之前提出:

describe("Todo Routes", function(){ 
    var route; 
    var rootScope; 
    var location; 
    var httpBackend; 

    beforeEach(function(){ 
     module('todoApp'); 

     inject(function($route, $location, $rootScope, $httpBackend){ 
      route = $route; 
      location = $location; 
      rootScope = $rootScope; 
      httpBackend = $httpBackend; 
     }); 
    }); 

    it("should navigate to todo list", function(){ 
     httpBackend.expectGET('app/html/listTodos.html').respond(200);//mimicking the AJAX call 
     expect(route.current).toBeUndefined(); 
     location.path('/todos'); 
     rootScope.$digest(); 
     expect(route.current.templateUrl).toBe('app/html/listTodos.html'); 
    }); 
});