在angularjs单元测试中,作用域一直未定义

我正在尝试对以下代码进行单元测试,我为下面的单元测试编写了以下代码,我尝试了很多工作方式,但是我不断遇到错误:

  

“无法读取未定义的属性'num'”

我不知道为什么范围设置不正确。如果您有任何想法,能否请您提供一些建议?

var angular = require('angular');
require('angular-mocks');

describe('test directive',function () {

    let $rootscope;
    let $compile;
    let scope;
    let newScope;
    let element;

    beforeEach(angular.mock.inject(function (_$compile_,_$rootscope_) {
        $compile = _$compile_;
        $rootscope = _$rootscope_;
    }));

    describe('test directive',function () {

        beforeEach(function () {
            newScope = $rootscope.$new();
            element = $compile('<test-directive></test-directive>')(newScope);
            newScope.$digest();
            scope = element.isolateScope();
        });

        fit('scope initialized',function () {
            expect(scope.num).toEqual(1);
        });

    });
});
module.exports = module.directive('testDirective',['$rootscope','$scope',function($rootscope,$scope) {

    return {
        template: require('./test.html'),restrict: 'E',controller: [
            '$scope',function ($scope) {
                    $scope.num = 1

                    $scope.sum = function(a,b) {
                        return a + b;
                    }

            }]
    }
}]);
ccf62904603 回答:在angularjs单元测试中,作用域一直未定义

scope变量为undefined,因为要测试的指令没有隔离范围。而是使用元素的范围:

    beforeEach(function () {
        newScope = $rootScope.$new();
        element = $compile('<test-directive></test-directive>')(newScope);
        newScope.$digest();
        ̶s̶c̶o̶p̶e̶ ̶=̶ ̶e̶l̶e̶m̶e̶n̶t̶.̶i̶s̶o̶l̶a̶t̶e̶S̶c̶o̶p̶e̶(̶)̶;̶
        scope = element.scope();
    });

    fit('scope initialized',function () {
        expect(scope.num).toEqual(1);
    });

请注意,指令存在致命缺陷。在给定范围内只能使用一次。

本文链接:https://www.f2er.com/3149918.html

大家都在问