gpt4 book ai didi

javascript - 如何测试 $rootScope.$emit 事件?

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:30:42 25 4
gpt4 key购买 nike

我在 abc Controller 中有以下代码:

   $rootScope.$on('selectedItem', function (event, data) {
vm.selectedItem = data;
});

调用函数在 xyz Controller 中:

  function doThis(){
$rootScope.$emit('selectedItem', 'somedata');
}

如何在 karma 测试中重现或模拟这种情况?

最佳答案

对于第一个 Controller (abc),您可以使用$rootScope.$on 收听它,您可以先$rootScope.$emit 它和 $scope.$digest() 它。这样您就可以在 $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');
});
});

对于第二个 Controller (xyz),您可以在 $rootScope.$emit监视。并且 expect 它在 xyz Controller 中被调用。像这样:

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');
});
});

关于javascript - 如何测试 $rootScope.$emit 事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43135747/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com