【问题标题】:Test a call to a passed callback in a directive测试对指令中传递的回调的调用
【发布时间】:2016-02-10 09:59:18
【问题描述】:

我正在尝试测试调用回调的逻辑,作为参数传递给指令。

我的指令是这样启动的:

 var directive = {
        ...
        scope: {
            onSave: '&'
        },
        controller: 'TmpViewCtrl',
        controllerAs: 'vm',
        bindToController: true // Isolate scope
    };

在控制器中,我使用将其存储为 vm 变量(John Pappas 样式指南)

function TmpViewCtrl($scope) {
    var vm = this;
    $scope.save = save;
    function save(element) {
        if (element !== undefined) {
            vm.onSave({element: element});
        }
    }

在我的测试中,我使用了以下 beforeEach:

 var dataMock = {
    onSave: function (elem) {
        return true;
    },
beforeEach(inject(function (_$compile_, _$rootScope_, _$controller_) {
    $compile = _$compile_;
    $rootScope = _$rootScope_.$new();
    $controller = _$controller_('TmpViewCtrl', {$scope: $rootScope}, dataMock);
    // Compile a piece of HTML containing the directive
    element = $compile("<div tmp-view ></div>")($rootScope);
    // fire all the watches, so the scope expressions will be evaluated
    $rootScope.$digest();

}));

我的测试看起来像

it('If save is triggered, callback should be called', function () {
    // Check that the compiled element contains the templated content
    var temp = {test: "test"};
    spyOn($rootScope, "save");
    spyOn($controller, "onSave");
    $rootScope.save(temp);
    expect($rootScope.save).toHaveBeenCalled();
    expect($controller.onSave).toHaveBeenCalled();
});

控制器的最后一行说 Expected spy onSave to have been called.,但它应该被调用吗?或者我正在检查错误的控制器范围?

【问题讨论】:

    标签: angularjs unit-testing angularjs-directive jasmine


    【解决方案1】:

    我来这里是为了寻找一种方法来模拟传递给 Angular 2 组件的回调。在@silbermm 建议的页面中找到了答案。基本上jasmin.createSpy 的诀窍是什么。

    $rootScope.save = jasmin.createSpy("save");
    $controller.onSave = jasmin.createSpy("onSave");
    expect($rootScope.save).toHaveBeenCalled();
    expect($controller.onSave).toHaveBeenCalled();
    

    【讨论】:

      【解决方案2】:

      我一直在寻找一种方法来做同样的事情。我偶然发现了一篇描述如何做到这一点的文章 - http://busypeoples.github.io/post/testing-components-angular-js/

      【讨论】:

        猜你喜欢
        • 2019-03-22
        • 2015-08-31
        • 2015-10-05
        • 2015-08-31
        • 2017-03-03
        • 1970-01-01
        • 2018-07-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多