Jasmine - 单元测试指令:获取'undefined'不是一个对象

时间:2015-06-25 11:00:20

标签: angularjs unit-testing jasmine karma-jasmine

我正在Jasmine采取婴儿步骤,请耐心等待任何明显的错误。我正在编写测试用例来检查控制器方法是否被调用,变换数据被调用,详情如下

我的指示

describe('directive - hh-star-ratings', function() {
'use strict';
angular.module('myModule', [])
.directive('myContainer', function() {
    return {
        restrict: 'E',
        priority: 100000,
        terminal: true,
        template: '<div></div>',
        controller: function($scope) {
            $scope.loadingData = true;
            this.stopLoading = function() {
                $scope.loadingData = false;
            };
        }
    }
});

var result_set = {
    //some data-transform-req
};

beforeEach(module('myModule'));

var element, scope, controller;

  beforeEach(inject(function($rootScope, $compile) {

      scope = $rootScope.$new();

      element = angular.element(
        '<my-container> <my-directive> </my-directive> </my-container>'
    );

    $compile(element)(scope);

    scope.$digest();

    controller = element.controller('myDirective');

  }));

it('should call the transformData', function() {
    controller.transformData(result_set);
    scope.$apply();
    scope.transformData.should.have.been.called;
});

我的规格

{{1}}

})

问题:当我运行测试时,出现以下错误

  

TypeError:'undefined'不是对象(评估'controller.transformData')

我做错了什么?提前感谢您的时间。

1 个答案:

答案 0 :(得分:0)

您在范围中定义函数transformData - 不在控制器中

    controller: [
        '$scope', '$controller',
        function ($scope, $controller) {
            $controller('otherController', {$scope: $scope})
                .columns(
                    $scope.x,
                    $scope.y,
                    $scope.series
                );
            this.transformData =  function(data) // <= change to this (controller)
            {
                /// does something;
                return data;
            };
        }
    ],