$routeUpdate 未在 angular 业力单元测试中广播?
$routeUpdate not broadcast in angular karma unit test?
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();
});
});
当 运行 测试时,"i was called" 从不记录。
也许您应该自己广播事件,然后测试如何处理它:
it('do call', function () {
scope.$emit('$routeUpdate', [1,2,3]);
scope.$apply();
expect....
});
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();
});
});
当 运行 测试时,"i was called" 从不记录。
也许您应该自己广播事件,然后测试如何处理它:
it('do call', function () {
scope.$emit('$routeUpdate', [1,2,3]);
scope.$apply();
expect....
});