如何让单元测试用例中定义范围?

问题描述 投票:0回答:0

我是Angularjs和单元测试的新手。我想知道如何在测试用例中定义范围变量。我有以下控制器。

(function () {
  app.controller('regionsController', regionsController);

  regionsController.$inject = [
    '$scope',
    'regions',
    'countryList',
    'statesList',
    'regionsService',
    '$timeout'
  ]

  function regionsController(
    $scope,
    regions,
    countryList,
    statesList,
    regionsService,
    $timeout
  ) {
    $scope.newRegions = [];
    $scope.regions = regions;
    $scope.selected = '';

$scope.emptyNewRegions = function () {
      $scope.newRegions = [];
     //other stuff
    }

 }
}())

下面是我在测试用例中做的事情。

describe('regionsController', function () {

    beforeEach(module('regionsApp'));
    describe('regionsController', function () {
        var ctrl, scope;
        beforeEach(inject(function ($controller, $rootScope) {
            scope = $rootScope.$new();
            ctrl = $controller('regionsController', { $scope:scope });
        }));
        describe('$scope.emptyNewRegions', function () {
            it('Testing emptyNewRegions function', function () {

                expect(ctrl).toBeDefined();
                scope.emptyNewRegions();
                expect(scope.newRegions).toBeDefined();
                expect(scope.newRegions.length).toBe(0);
            });
        });
    });
});

我得到这个错误。

  <Jasmine>
        Expected undefined to be defined.
        <Jasmine>
        unit/regionsTest.js:13:41
        <Jasmine>
        TypeError: undefined is not an object (evaluating 'scope.emptyNewRegions') in unit/regionsTest.js (line 14)
        unit/regionsTest.js:14:22
        <Jasmine>
PhantomJS 2.1.1 (Windows 8): Executed 1 of 1 (1 FAILED) (0.006 secs / 0.005 secs)
TOTAL: 1 FAILED, 0 SUCCESS

请让我知道我如何能做到这一点。先谢谢你。

angularjs unit-testing karma-jasmine
© www.soinside.com 2019 - 2024. All rights reserved.