首页 文章

TypeError:范围未定义Karma-jasmine-angular单元测试

提问于
浏览
1

我是 karma-jasmine 的新手,并试图开发一个演示测试用例 . 我在 'it' 收到 scope is not defined 的错误 . 我已经阅读了以下具有相同问题的链接,但它并没有帮助我处理我的测试用例 .

Error Karma 'undefined' scope variable in beforeEach

TypeError: $scope is undefined in Angular controller unit test with Jasmine

这是我的karma.conf.js

module.exports = function(config) {
      config.set({

    exclude)
        basePath: '',


        frameworks: ['jasmine'],

     files: [
          'js/angular.js',
          'js/angular-mocks.js',
          'app.js',
          'test/**/*Spec.js'
        ],
        exclude: [
        ],

        preprocessors: {
        },
        reporters: ['progress'],
        port: 9876,

        colors: true,

    config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
        logLevel: config.LOG_INFO,

        autoWatch: false,


        browsers: ['Firefox'],

        singleRun: false 
      });
    };

这是我的mySpec.js,其中编写了测试代码

describe('myApp', function() {

    beforeEach(module('myApp'));

    describe('HelloWorldController', function() {

        var scope,HelloWorldController;

        beforeEach(inject(function ($rootScope, $controller) {
            scope = $rootScope.$new();
            HelloWorldController = $controller('HelloWorldController', {
                $scope: scope
            });
        }));

        it('should assign message to hello world', function () {
            expect(scope.greeting).toEqual('Hello World!');
        });
    });
});

这是我的app.js,其中定义了控制器 .

var myApp = angular.module('myApp',[]);
myApp.controller('HelloWorldController', ['$scope', function($scope) {
    $scope.greeting = 'Hello World!';
}]);

我得到的错误是,

TypeError:未定义 /home/abc/WebstormProjects/test1/test/basic/mySpec.js(第17行)

我不知道我在哪里弄错了 . 请引导我解决这个问题 .

提前致谢 .

1 回答

  • 1

    你在这里遇到的一个问题是拼写错误 . 'scope'未定义,因为在您的控制器注入中,您将其定义为'$ scope',但您的expect语句引用了'scope':

    describe('myApp', function() {
    
        beforeEach(module('myApp'));
    
        describe('HelloWorldController', function() {
    
            var scope,HelloWorldController;
    
            beforeEach(inject(function ($rootScope, $controller) {
                scope = $rootScope.$new();
                HelloWorldController = $controller('HelloWorldController', {
                    $scope: scope
                });
            }));
    
            it('should assign message to hello world', function () {
                expect(scope.greeting).toEqual('Hello World!');
            });
        });
    });
    

相关问题