UI路由器附加功能会因意外结果错误而破坏我的单元测试?

时间:2014-12-31 18:31:15

标签: javascript angularjs unit-testing angular-ui-router karma-runner

问题:

- 为什么我的测试在安装ui-router-extras(不是普通的ui-router)时失败?

- 如何使用ui-router-extras并仍然通过我的测试?


如果你想快速安装,请使用yeoman + angular-fullstack-generator + bower install ui-router-extras

I found a similar issue with normal ui-router

  • 幸运的是,ui-router normal在我的测试中运行正常。
  • 安装ui-router-extras后,我收到错误

Error log

如果我卸载ui-router.extras,那么这个测试通过就好了: enter image description here

UPDATED for $ urlRouterProvider TEST 的beforeEach模块 继承了我的考验:

'use strict';

describe('Controller: MainCtrl', function () {

  // load the controller's module
  beforeEach(module('morningharwoodApp'));
  beforeEach(module('socketMock'));

  var MainCtrl,
      scope,
      $httpBackend;

  // Initialize the controller and a mock scope


  beforeEach(
    inject( function (_$httpBackend_, $controller, $rootScope) {
      $httpBackend = _$httpBackend_;
      $httpBackend.expectGET('/api/things')
        .respond(['HTML5 Boilerplate', 'AngularJS', 'Karma', 'Express']);

      scope = $rootScope.$new();
      MainCtrl = $controller('MainCtrl', {
        $scope: scope
      });
    }),
    module(function ($urlRouterProvider) {
      $urlRouterProvider.otherwise( function(){ return false; });
    })
  );



  it('should attach a list of things to the scope', function () {
    $httpBackend.flush();
    expect(scope.awesomeThings.length).toBe(4);
  });
});

这是我的karma.conf

module.exports = function(config) {
  config.set({
    // base path, that will be used to resolve files and exclude
    basePath: '',

    // testing framework to use (jasmine/mocha/qunit/...)
    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    files: [
      'client/bower_components/jquery/dist/jquery.js',
      'client/bower_components/angular/angular.js',
      'client/bower_components/angular-mocks/angular-mocks.js',
      'client/bower_components/angular-resource/angular-resource.js',
      'client/bower_components/angular-cookies/angular-cookies.js',
      'client/bower_components/angular-sanitize/angular-sanitize.js',
      'client/bower_components/lodash/dist/lodash.compat.js',
      'client/bower_components/angular-socket-io/socket.js',
      'client/bower_components/angular-ui-router/release/angular-ui-router.js',
      'client/bower_components/famous-polyfills/classList.js',
      'client/bower_components/famous-polyfills/functionPrototypeBind.js',
      'client/bower_components/famous-polyfills/requestAnimationFrame.js',
      'client/bower_components/famous/dist/famous-global.js',
      'client/bower_components/famous-angular/dist/famous-angular.js',
      'client/app/app.js',
      'client/app/app.coffee',
      'client/app/**/*.js',
      'client/app/**/*.coffee',
      'client/components/**/*.js',
      'client/components/**/*.coffee',
      'client/app/**/*.jade',
      'client/components/**/*.jade',
      'client/app/**/*.html',
      'client/components/**/*.html'
    ],

    preprocessors: {
      '**/*.jade': 'ng-jade2js',
      '**/*.html': 'html2js',
      '**/*.coffee': 'coffee',
    },

    ngHtml2JsPreprocessor: {
      stripPrefix: 'client/'
    },

    ngJade2JsPreprocessor: {
      stripPrefix: 'client/'
    },

    // list of files / patterns to exclude
    exclude: [],

    // web server port
    port: 8080,

    // level of logging
    // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
    logLevel: config.LOG_INFO,


    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: false,


    // Start these browsers, currently available:
    // - Chrome
    // - ChromeCanary
    // - Firefox
    // - Opera
    // - Safari (only Mac)
    // - PhantomJS
    // - IE (only Windows)
    browsers: ['PhantomJS'],


    // Continuous Integration mode
    // if true, it capture browsers, run tests and exit
    singleRun: false
  });
};

4 个答案:

答案 0 :(得分:10)

这可能是某些组件依赖$state的结果,在这种情况下$state将被实例化,并且将执行默认路由。这就是正在获取其中一个控制器main.html的模板的原因。

要绕过此操作,请使用假人替换go()transitionTo()$state方法:

beforeEach( inject( function ( _$state_ ) {
        state = _$state_;
        spyOn( state, 'go' );
        spyOn( state, 'transitionTo' );
    } ) );

答案 1 :(得分:4)

这是一个替代解决方案,它不会影响ui-router的transitionTo功能。


首先,可以通过以下步骤重现失败的场景:

npm install yo generator-angular-fullstack;
yo angular-fullstack

通过将此行添加到client / app / app.js来注入$ state服务:

angular.module("yoAppName").run(function($state) {});

此时,调用grunt karma报告Unexpected request: GET app/main/main.html,因为UI-Router已自举并尝试加载默认路由,该路由请求路由模板。


要解决此问题,请告知UI-Router延迟将URL同步到状态,因此我们不会加载默认路由。在控制器规范中,将$urlRouterProvider.deferIntercept();添加到测试初始化​​代码:

beforeEach(module('uiRouterExtrasKarmaBugApp'));
// Add the following line
beforeEach(module(function($urlRouterProvider) { $urlRouterProvider.deferIntercept(); }));

答案 2 :(得分:1)

1)您的测试失败,因为ui-router-extras正在向app/main/main.html发出意外的http GET请求,因此测试失败。

2)实际上你在链接的问题上有很多建议。我假设额外调用加载默认路由的模板,即。 otherwise。所以重写它可能会解决问题:

beforeEach(module(function ($urlRouterProvider) {
    $urlRouterProvider.otherwise(function(){return false;});
}));

答案 3 :(得分:1)

实际上有两种解决方案......在模块声明之后。

  1. 您可以添加:

    beforeEach(module('stateMock'));

  2. 或者您可以手动延迟拦截:

    beforeEach(module(function($urlRouterProvider) { $urlRouterProvider.deferIntercept(); }));