$routeUpdate未在角因果报应单元测试中广播

$routeUpdate not broadcast in angular karma unit test?

本文关键字:单元测试 广播 因果报应 routeUpdate      更新时间:2023-09-26

app.js

  'use strict';
angular
  .module('scrCliApp', [
    'ngRoute',
    'ui.bootstrap'
  ])
  .config(function ($routeProvider) {
    $routeProvider
      .when('/search', {
        templateUrl: 'views/main.html',
        controller: 'MainCtrl',
        reloadOnSearch: false
      })
      .otherwise({
        redirectTo: '/search'
      });
  });

main.js控制器

angular.module('scrCliApp')
  .controller('MainCtrl', function ($scope) {
    $scope.$on('$routeUpdate', function(/*scope, next, current*/) {
      console.log('i was called'); //never logs
    });
  });

main.js测试

    'use strict';
describe('Controller: MainCtrl', function () {
  // load the controller's module
  beforeEach(module('scrCliApp'));
  var MainCtrl,
    scope,
    rootScope,
    location;
  // Initialize the controller and a mock scope
  beforeEach(inject(function ($controller, $rootScope, $location) {
    rootScope = $rootScope;
    location = $location;
    scope = $rootScope.$new();
    MainCtrl = $controller('MainCtrl', {
      $scope: scope
    });
  }));
  it('do call', function () {
    location.search('q', 'b');
    scope.$apply();
  });
});

运行测试时,"我被调用了"从不记录。

也许你应该自己广播事件,然后测试如何处理它:

it('do call', function () {
    scope.$emit('$routeUpdate', [1,2,3]);
    scope.$apply();
    expect....
});