问题
I have below code in abc
controller:
$rootScope.$on('selectedItem', function (event, data) {
vm.selectedItem = data;
});
And the caller function is in xyz
controller:
function doThis(){
$rootScope.$emit('selectedItem', 'somedata');
}
How can I reproduce or mock this scenario in karma test?
回答1:
For first controller (abc
), where you listen to it using $rootScope.$on
, you can first $rootScope.$emit
it and $scope.$digest()
it. So that you can receive it in $on
.
var rootScope;
beforeEach(inject(function(_$rootScope_) {
rootScope = _$rootScope_;
}));
describe("some function", function() {
it("should receive selectedItem with $on", function() {
rootScope.$emit('selectedItem', 'somedata');
$scope.$digest();
expect(vm.selectedItem).toEqual('somedata');
});
});
And for second controller (xyz
), You can spy
on $rootScope.$emit
. And expect
it to be called in xyz
controller. Like this:
var rootScope;
beforeEach(inject(function(_$rootScope_) {
rootScope = _$rootScope_;
spyOn(rootScope, '$emit');
}));
describe("doThis function", function() {
it("should $emit selectedItem", function() {
vm.doThis(); // or if you use $scope, call it that way
expect(rootScope.$emit).toHaveBeenCalledWith('selectedItem');
});
});
回答2:
Using Jasmine, it could look like this:
var rootScope;
beforeEach(inject(function($injector) {
rootScope = $injector.get('$rootScope');
spyOn(rootScope, '$emit');
}));
describe("$rootScope event testing", function() {
it("should $emit selectedItem", function() {
expect(rootScope.$emit).toHaveBeenCalledWith('selectedItem');
});
});
来源:https://stackoverflow.com/questions/43135747/how-can-i-test-rootscope-emit-event