单元测试间谍$ emit

Maa*_*ten 16 unit-testing angularjs angularjs-directive

我正试图窥探指令的$ emit,但不知怎的,我不能让间谍'听'$ emit.

这是我的指令控制器中的代码:

$scope.$on('send', function () {
    console.log('called');
    $scope.$emit('resultSend', {'ok': true, 'data': ''});
});
Run Code Online (Sandbox Code Playgroud)

这是我的单元测试:

var $rootScope, $compile, elm, element;

beforeEach(inject(function ($injector) {
    $rootScope = $injector.get('$rootScope');
    $compile = $injector.get('$compile');
    elm = angular.element('<test></test>');
    element = $compile(elm)($rootScope);
}));


it('should listen for the send broadcast and emit the resultSend', function () {
    spyOn($rootScope, '$emit');
    $rootScope.$broadcast('send');
    expect($rootScope.$emit).toHaveBeenCalledWith('resultSend');
});
Run Code Online (Sandbox Code Playgroud)

console.log输出('called')由Karma打印出来,所以我猜单元测试广播事件确实有效.

这是否与$ emit相关而不是向下播放,如果是这样,我该如何捕获它,如果不是,我该如何处理这种情况呢?

ten*_*ent 18

根据该文档在这里,你在你的区别的理解是否正确$emit$broadcast.但是,我认为问题出在你的使用$scope$rootScope.您$rootScope将位于范围层次结构的顶层.我猜测(只是通过查看你的片段而不能看到所有代码)$scope你的控制器中的你是一个嵌套控制器,这意味着$scope你的控制器中是应用程序的孩子$rootScope.

因此,当您的单元测试对该$rootScope.$emit功能进行监视时,它实际上并没有监视您的控制器的$scope.$emit()呼叫.这两个"范围"是不同的,不一样的.因此,您需要模拟$scope为控制器提供的内容,然后对其进行操作spyOn.

例如,在你的beforeEach:

var ctrl, scope;

beforeEach(function() {
    module('<INSERT YOUR CONTROLLERS MODULE NAME HERE>'); 
    inject(function($rootScope, $controller) {
        scope = $rootScope.$new();
        ctrl = $controller('<CTRL NAME HERE>', {$scope: scope});
    });
});
Run Code Online (Sandbox Code Playgroud)

这段代码实际上会创建一个"模拟"范围变量,并将该对象提供给您的控制器,然后您可以使用它来执行间谍和其他操作.如:

spyOn(scope, '$emit');
// do whatever triggers the "$emit" call
expect(scope.$emit).toHaveBeenCalledWith('resultSend');
Run Code Online (Sandbox Code Playgroud)

我很确定应该解决你的问题.如果需要更多解释,请告诉我.