Jasmine:Controller已定义,但其方法未定义

时间:2016-01-21 14:56:47

标签: javascript angularjs unit-testing jasmine

我正在测试AngularJS指令的控制器。

describe('The directive', function() {
    var element,
        scope;

    beforeEach(module('app'));
    beforeEach(module('path/to/theDirective'));

    beforeEach(inject(function($compile, $rootScope) {
        element = angular.element('<div args="args" the-directive ></div>');
        scope = $rootScope;
        $compile(element)(scope);
        scope.args = {
            availableValues : [1, 2, 3],
            key : 'id',
            selectedValues : [],
            searchText : '',
            flag: false
        };
        scope.$digest();        
    }));

    it('should compile', function() {
        expect(element.html()).not.toBeNull();
    });

    describe('directive controller', function() {
        var controller;

        beforeEach(inject(function($controller) {
            controller = element.controller('theDirective', {
                $scope: scope
            });
        }));

        it('should exist', function() {
            expect(controller).not.toBeNull();
            expect(controller).toBeDefined();
            expect(scope.disableAddButton()).toBeDefined();
        });
    });
});

第一个it块传递,因此指令正在成功编译。第二个describe块未通过。第二个describe it块中的前两个断言通过,但第三个断言没有通过。它正在返回TypeError: 'undefined' is not a function (evaluating 'scope.disableAddButton()')。是否可能未正确注入控制器,或者是否需要进行更多设置?

1 个答案:

答案 0 :(得分:1)

事实证明,范围需要隔离,因为指令的控制器是私有功能。

mAdapter.notifyDataSetChanged();之后添加scope = element.isolateScope() || element.scope();可以解决问题。此外,将控制器声明移动到第一个scope.$digest();块并不是一个坏主意。

固定测试看起来像这样:

beforeEach