Angularjs 测试对指令中传递的回调的调用

Angularjs 测试对指令中传递的回调的调用,angularjs,unit-testing,angularjs-directive,jasmine,Angularjs,Unit Testing,Angularjs Directive,Jasmine,我正在尝试测试调用回调的逻辑,该回调作为参数传递给指令 我的指令是这样开始的: var directive = { ... scope: { onSave: '&' }, controller: 'TmpViewCtrl', controllerAs: 'vm', bindToController: true // Isolate scope }; 在控制器

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

我的指令是这样开始的:

 var directive = {
        ...
        scope: {
            onSave: '&'
        },
        controller: 'TmpViewCtrl',
        controllerAs: 'vm',
        bindToController: true // Isolate scope
    };
在控制器i中,使用将其存储为vm变量(John Pappas styleguide)

在我的测试中,我在每次测试之前都会使用以下选项:

 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();

}));
控制员最后一行说
预期已调用spy onSave。
,但是否应调用它?或者我正在检查假控制器范围?

我正在寻找一种方法来做同样的事情。我偶然发现了一篇描述如何做的文章-

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

$rootScope.save = jasmin.createSpy("save");
$controller.onSave = jasmin.createSpy("onSave");
expect($rootScope.save).toHaveBeenCalled();
expect($controller.onSave).toHaveBeenCalled();
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();
});
$rootScope.save = jasmin.createSpy("save");
$controller.onSave = jasmin.createSpy("onSave");
expect($rootScope.save).toHaveBeenCalled();
expect($controller.onSave).toHaveBeenCalled();