如何在Jasmine测试中测试$ scope。$ on事件? [英] How can I test a $scope.$on event in a Jasmine test?

查看:153
本文介绍了如何在Jasmine测试中测试$ scope。$ on事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是单元测试控制器,我想测试一个事件处理程序。假设我的控制器如下:

I am unit testing a controller and I want to test an event handler. Say my controller looks like:

myModule.controller('MasterController', ['$scope', function($scope){
    $scope.$on('$locationChangeSuccess', function() {
        $scope.success = true;
    });
}]);

我会在我的Jasmine测试中广播吗?我会发射它吗?是否有可接受的标准?

Would I broadcast that in my Jasmine test? Would I emit it? Is there an accepted standard?

推荐答案

我提出的解决方案如下:

The solution I came up with is as follows:

describe('MasterController', function() {
    var $scope, $rootScope, controller, CreateTarget;

    beforeEach(function() {
        inject(function($injector) {
            $rootScope = $injector.get('$rootScope');
            $scope = $rootScope.$new();

            var $controller = $injector.get('$controller');

            CreateTarget = function() {
                $controller('MasterController', {$scope: $scope});
            }
        });
    });

    describe('$locationChangeSuccess', function() {
        it('should set $scope.success to true', function() {
            controller = CreateTarget();
            $rootScope.$broadcast('$locationChangeSuccess');
            expect($scope.success).toBe(true);
        });
    });
});

这篇关于如何在Jasmine测试中测试$ scope。$ on事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆