任何人都可以帮助我完成以下场景,如何使用karma angular实现此目的。 $ stateChangeSuccess很简单,没有任何回调函数。但是找到stateChangeStart很难。
$scope.$on('$stateChangeStart', function (event, toState, toParams, fromState) {
if (fromState.name.match('test.abc') && ($scope.validate())) {
event.preventDefault();
}
});
尝试类似下面的内容,但我不确定,我是在正确的道路上
var fromState = {name: 'test.abc'};
var toState = {name: 'test.xyz'};
scope.$on('$stateChangeStart');
expect(scope.$on).toHaveBeenCalled();
expect(fromState.name)toBe('test.abc');
/* expect event prevent default? */
答案 0 :(得分:1)
如果它在控制器内部,那么你可以简单地spyOn($ scope,'$ on');
这是一个简单的例子:
angular.module('app', []);
angular
.module('app')
.controller('Example', function ($scope) {
$scope.$on('event', (event, args) => {
$scope.args = args;
event.stopPropagation();
});
});
describe('Example Controller', () => {
let Example;
let $scope;
beforeEach(module('app'));
beforeEach(inject(($controller, $rootScope) => {
$scope = $rootScope.$new();
spyOn($scope, '$on');
$scope.$on.and.callThrough();
Example = $controller('Example', {
$scope
});
}));
it('sets args on $scope when event is fired', () => {
const args = 'args';
$scope.$emit('event', args);
expect($scope.args).toBe('args');
});
it('event callback stops propagation', () => {
const [, callback] = $scope.$on.calls.argsFor(0);
const event = jasmine.createSpyObj('event', ['stopPropagation']);
callback(event);
expect(event.stopPropagation).toHaveBeenCalled();
});
});
<script src='https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.4.1/jasmine.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.4.1/jasmine-html.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.4.1/boot.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.5/angular.min.js'></script>
<script src='https://code.angularjs.org/1.5.5/angular-mocks.js'></script>
<link rel='stylesheet prefetch' href='https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.4.1/jasmine.css'>