javascript - 测试 Angular $emit 和 $on 事件

标签 javascript angularjs jasmine

我正在尝试为 Controller 中的事件编写单元测试。

下面是我的 Controller

myApp.controller('ParentCtrl', ['$scope', function ($scope) {
    $scope.message = "Some text in parent";
    $scope.$on("update_parent_controller", function(event, message){
        $scope.message = message;
    });

}])
.controller('ChildCtrl', ['$scope', function ($scope) {
    $scope.clickFunction = function() {
    $scope.message = "Parent updated from child controller";

        $scope.$emit('update_parent_controller', $scope.message);
    }

}]);

下面是我正在尝试编写的测试

describe("Hello Controller Test", function () {
    var ctrl, scope;

    beforeEach(module("myApp"));

    beforeEach(inject(function ($controller, $rootScope) {
        scope = $rootScope.$new();
        spyOn(scope, '$on');

        ctrl = $controller("ParentCtrl", {
            $scope : scope
        });
    }));

    it('should change ParentCtrl message property from child ctrl', function (){

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

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

        expect(scope.$on).toHaveBeenCalled();
        expect(scope.message).toBe('Ralf ninja turtle'); //Getting err here
    });
});

我期待更新父 Controller 中的消息, 但是测试在 expect(scope.message).toBe('Ralf ninja turtle');

最佳答案

您需要在调用 $emit 之后调用 $scope.$apply()。这会在应用程序中自动发生,但需要在测试中显式调用。

关于javascript - 测试 Angular $emit 和 $on 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32785540/

相关文章:

javascript - animate.css循环2个不同的动画

javascript - 单元测试如何访问对象属性

html - 使用 Angular 微调器设置固定的顶部位置

javascript - 使用 ng-change 验证现有用户 ID

javascript - Jasmine 有 createSpy() 返回模拟对象

javascript - 提交 HTML 表单后从数组中提取数据(按键事件)

javascript - 如何在 angularjs 的 View 中使用 ng-if 值检查 null?

html - 无法在 bootstrap 模式中将输入集中在 qtip 中

javascript - 如何根据 Jasmine 单元测试中的其他对象测试功能

javascript - 带有注入(inject)服务的单元测试 Angular Controller