You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AngularJS路由测试报错:Unknown provider: $routeProvider <- $route 求助

AngularJS路由Jasmine测试报错:$injector:unpr 问题排查与解决

我帮你捋清楚这个问题的来龙去脉,以及对应的解决办法:

问题回顾

你在给AngularJS路由写Jasmine测试时,执行karma start后遇到了这个注入错误:

Error: [$injector:unpr] Unknown provider: $routeProvider <- $route

你的代码结构看起来没问题,所有JS都用IIFE封装,但测试的初始化顺序和依赖加载有两处关键问题。

你的相关代码

测试代码

it('should map routes to controllers and templates', function() { 
  inject(function($route) { 
    module('igt'); 
    expect($route.routes['/'].controller).toBe('mainPageCtrl'); 
    expect($route.routes['/'].templateUrl).toEqual('html/pages/main.html'); 
    // otherwise redirect to 
    expect($route.routes[null].redirectTo).toEqual('/') 
  }); 
});

路由配置片段

(function () { 
  'use strict'; 
  angular 
    .module('igt') 
    .config(configure); 

  configure.$inject = ['$routeProvider', '$httpProvider']; 
  function configure($routeProvider, $httpProvider) { 
    $routeProvider 
      .when('/', { 
        templateUrl: 'html/pages/main.html', 
        controller: 'mainPageCtrl' 
      }) 
  }
})();

Karma配置文件片段

// list of files / patterns to load in the browser
files: [
  '../../node_modules/angular/angular.js',
  '../../node_modules/angular-mocks/angular-mocks.js',
  '../app.js',
  '../router.js',
  'unit/*.js'
],

问题原因与修复步骤

1. 测试初始化顺序错误(核心问题)

在AngularJS的测试规范里,module()是用来加载并配置模块的,必须在inject()之前执行——inject()的作用是从已经加载好的模块中获取服务实例。你现在把module('igt')放在inject()内部,相当于还没加载模块就去请求$route服务,Angular自然找不到对应的提供者,就抛出了这个错误。

2. 缺失ngRoute依赖

AngularJS的路由功能不是核心自带的,它属于独立的ngRoute模块,你需要确保两处配置:

  • 主模块igt声明依赖ngRoute:
    // 在你的app.js里,模块定义要加上['ngRoute']
    angular.module('igt', ['ngRoute']);
    
  • Karma文件列表中引入angular-route.js:
    files: [
      '../../node_modules/angular/angular.js',
      '../../node_modules/angular-route/angular-route.js', // 新增这一行
      '../../node_modules/angular-mocks/angular-mocks.js',
      '../app.js',
      '../router.js',
      'unit/*.js'
    ],
    

3. 修正后的测试代码

把模块加载移到beforeEach里(这是Angular测试的标准写法,确保每个测试用例都能拿到干净的模块环境),调整后的测试代码如下:

describe('Route configuration for igt app', function() {
  // 每个测试前先加载目标模块
  beforeEach(module('igt'));

  it('should map root route to correct controller and template', inject(function($route) {
    expect($route.routes['/'].controller).toBe('mainPageCtrl');
    expect($route.routes['/'].templateUrl).toEqual('html/pages/main.html');
    // 验证otherwise规则
    expect($route.routes[null].redirectTo).toEqual('/');
  }));
});

做完以上三点调整后,再执行karma start,这个注入错误应该就能解决了。

内容的提问来源于stack exchange,提问作者BT101

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:38:36