单元测试AngularJS路由抛出错误:意外请求

时间:2013-07-28 07:48:39

标签: unit-testing angularjs karma-runner

以下是我的Jasmine RoutesSpec.js

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');
});

执行此规范会引发以下错误:

  

错误:意外请求:GET ../html/listTodos.html           没有更多的要求               在错误()               在$ httpBackend(C:/Learn/Javascript/todo_app/libs/angular-mocks.js:934:9)               在sendReq(C:/Learn/Javascript/todo_app/libs/angular.js:9146:9)               $ http(C:/Learn/Javascript/todo_app/libs/angular.js:8937:17)               在函数。$ http。(匿名函数)(C:/Learn/Javascript/todo_app/libs/angular.js:9080:18)               $ 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)               在C:/Learn/Javascript/todo_app/libs/angular.js:6883:26               at Object.Scope。$ eval(C:/Learn/Javascript/todo_app/libs/angular.js:8057:28)

1 个答案:

答案 0 :(得分:2)

这意味着有一个AJAX调用来获取模板。 $ httpBackend.expectGET(' app / html / listTodos.html')。在调用path()之前可以放置response(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');
    });
});