unit-testing - 使用 Jasmine 测试时,如何触发 $emit 来测试 Controller 中的 $on 监听器?

标签 unit-testing angularjs jasmine

我有一个 Controller ,想用 Jasmine 测试它。我要测试的 Controller 范围内有一个 $on 监听器。如何触发 $emit 事件以运行 $on 监听器?

myApp.controller('superCtrl', function ($scope) {
    $scope.hero = 'Rafael ninja turtle';

    $scope.$on('change_hero', function (event, new_hero) {
        $scope.hero = new_hero;
    });
});

当 'change_hero' 事件发生时,测试 $on 监听器是否正常工作:
describe('Super controller', function () {
    var $scope,
        super_controller;

    beforeEach(function(){

        module('myApp');

        inject(function($rootScope, $controller){
            $scope = $rootScope.$new();

            super_controller = $controller('superCtrl', {$scope: $scope});

            spyOn($scope, '$on');
        });

    });

    it('should change change hero on change_hero event', function (){

        var new_hero = 'Ralf ninja turtle',
            sub_scope = $scope.$new();

        sub_scope.$emit('change_hero', new_hero);

        expect($scope.$on).toHaveBeenCalled();
        expect($scope.hero).toBe('Ralf ninja turtle');
    });

});

最佳答案

看起来您需要在创建 Controller 之前调用 spyOn。
此外,您应该调用 andCallThrough() 否则不会调用真正的方法并且您的测试将失败

关于unit-testing - 使用 Jasmine 测试时,如何触发 $emit 来测试 Controller 中的 $on 监听器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19859829/

相关文章:

reactjs - 如何在 enzyme 测试用例中模拟拖放?

javascript - 我可以像任何其他库一样将 JointJS 作为 AngularJS 模块注入(inject)吗?

javascript - 如果我对 'Cannot read property ' *** *' of undefined' 没问题怎么办?

junit - jasmine.JUnitXmlReporter 报告可视化工具

javascript - 使用磁带/ES6 单元测试测试 AMD 模块?

python - 如何在 Django 中测试手动数据库事务代码?

java - 如何模拟EntityManager?

javascript - AngularJS比较两个日期

angularjs - 通过右键菜单在 Web Storm 中运行单个 Karma Jasmine 测试

node.js - 使用 jasmine 和 node.js 模拟文件系统