在指令

时间:2016-02-10 09:59:18

标签: angularjs unit-testing angularjs-directive jasmine

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

我的指令是这样开始的:

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

在Controller i中使用将其存储为vm变量(John Pappas styleguide)

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

在我的测试中使用以下之前的每个:

 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.,但它应该被称为?或者我正在检查错误的控制器范围?

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

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

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