【问题标题】:scope keeps being undefined in angularjs unit-testing范围在angularjs单元测试中一直未定义
【发布时间】:2019-11-06 17:56:32
【问题描述】:

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

'无法读取属性'num' of undefined'

我不知道为什么没有正确设置范围。如果您对此有任何想法,可以给一些建议吗?

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;
                    }

            }]
    }
}]);

【问题讨论】:

  • 如果指令中没有使用 $rootScope,为什么还要引用它?
  • 其实我是用来播的,只是这里不包括而已。
  • 我已经调查过了,但还是有问题。

标签: angularjs unit-testing scope angularjs-scope


【解决方案1】:

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

请注意该指令有一个致命的缺陷。它只能在给定范围内使用一次。

【讨论】:

  • 是的,我可以从中得到一些东西,但是它返回的是 ChildScope 而不是 Scope,你知道为什么会这样吗?
  • 它返回一个ChildScope,因为它继承了$rootScope的属性。
  • newScope 应该是 Childscope 但范围应该是特定于元素的范围,但它不是。
  • 当指令定义对象中省略 scope 属性时,不会为指令创建范围。见AngularJS Comprehensive Directive API Reference - scope
  • 其实我试过了,scope:{}这样。但还是不行,以后再研究。
猜你喜欢
  • 2014-03-22
  • 1970-01-01
  • 2014-12-06
  • 2015-06-29
  • 2019-06-19
  • 2015-06-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多