javascript - Karma 未按预期运行 Angular 测试

标签 javascript angularjs karma-runner karma-jasmine

我是 Karma 新手,因此错误可能非常基本。

这是我的 karma.conf.js 文件

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

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',


    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine'],


    // list of files / patterns to load in the browser
    files: [
      'bower_components/angular/angular.js',
      'bower_components/angular-mocks/angular-mocks.js',
      'bower_components/angular-resource/angular-resource.js',
      'app/index.js',
      'app/heroDetail.js',
      'app/*.js',
      'test/*.js',
      'app/**/*.js',
      'test/**/*.js'
    ],


    // list of files to exclude
    exclude: [
    ],


    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
    },


    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['progress'],


    // web server port
    port: 9876,


    // enable / disable colors in the output (reporters and logs)
    colors: true,


    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,


    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,


    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['Chrome'],


    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false,

    // Concurrency level
    // how many browser should be started simultaneous
    concurrency: Infinity
  })
}

app 目录 中,我的 jshtml 文件驻留在其中。

enter image description here

index.html 看起来像:

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Example - example-heroComponentSimple-production</title>

  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>

  <script src="index.js"></script>
  <script src="heroDetail.js"></script>

</head>
<body ng-app="heroApp">
  <!-- components match only elements -->
<div ng-controller="MainCtrl as ctrl">
  <b>Hero</b><br>
  <hero-detail hero="ctrl.hero"></hero-detail>
</div>
</body>
</html>

index.js 看起来像:

(function(angular) {
  'use strict';
    angular.module('heroApp', []).controller('MainCtrl', function MainCtrl() {
        this.hero = {
            name: 'Miles Bronson'
        };
    });
})(window.angular);

现在在我尝试过的测试规范文件中:

describe('MainController',function(){
    var $rootScope,
        $scope,
        controller;
    beforeEach(function(){
        module('heroApp');

        inject(function($injector){
            $rootScope = $injector.get('$rootScope');
            $scope = $rootScope.$new();
            controller = $injector.get('$controller')('MainCtrl',{$scope: $scope});
        });
    });

    it('should initialize name of the hero',function(){
        expect($scope.hero.name).toEqual('Miles Bronson'); 
    });

    it('should not pass',function(){
        expect($scope.hero.name).toEqual('Milesl Bronsonkk'); 
    });
});

现在,当我执行 karma start karma.conf.js 时,它会显示

$ karma start karma.conf.js
18 01 2017 19:58:51.928:WARN [karma]: No captured browser, open http://localhost:9876/
18 01 2017 19:58:51.943:INFO [karma]: Karma v1.4.0 server started at http://0.0.0.0:9876/
18 01 2017 19:58:51.943:INFO [launcher]: Launching browser Chrome with unlimited concurrency
18 01 2017 19:58:51.953:INFO [launcher]: Starting browser Chrome
18 01 2017 19:58:54.145:INFO [Chrome 55.0.2883 (Windows 8.1 0.0.0)]: Connected on socket oOKBdNiWr9pVmcqnAAAA with id 12481546
Chrome 55.0.2883 (Windows 8.1 0.0.0) MainController should initialize name of the hero FAILED
        TypeError: Cannot read property 'name' of undefined
            at Object.<anonymous> (test/controllers/main-controller-spec.js:45:27)
Chrome 55.0.2883 (Windows 8.1 0.0.0) MainController should not pass FAILED
        TypeError: Cannot read property 'name' of undefined
            at Object.<anonymous> (test/controllers/main-controller-spec.js:49:27)
Chrome 55.0.2883 (Windows 8.1 0.0.0): Executed 2 of 2 (2 FAILED) ERROR (0.052 secs / 0.038 secs)

但是第二个应该失败,而第一个应该通过?为什么会出现这种意外行为?

我做错了什么?

chrome浏览器也没有多大帮助......

enter image description here

请帮忙!

最佳答案

我认为您可能遇到了嵌套问题,并且描述了太多...

看起来你想要更多类似这样的东西,其中 beforeEach 在每次测试之前触发:

describe('MainController',function(){
    var $rootScope,
        $scope,
        controller;
    beforeEach(function(){
        module('heroApp');

        inject(function($injector){
            $rootScope = $injector.get('$rootScope');
            $scope = $rootScope.$new();
            controller = $injector.get('$controller')('MainCtrl',{$scope: $scope});
        });
    });

    it('should initialize name of the hero',function(){
        expect($scope.hero.name).toEqual('Miles Bronson'); 
    });

    it('should not pass',function(){
        expect($scope.hero.name).toEqual('Milesl Bronsonkk'); 
    });
});

此外,您并没有真正在 Controller 中使用全局范围...我认为您的测试在设置和断言方面可以简单得多。像这样的东西:

describe('TestMainController',function(){
    beforeEach(module('heroApp'));

    var $controller;

    beforeEach(inject(function(_$controller_){
      $controller = _$controller_;
    }));

    it('should initialize name of the hero',function(){
      var controller = $controller('MainController');
      expect(controller.hero.name).toEqual('Miles Bronson'); 
    });

    it('should not pass',function(){
      var controller = $controller('MainController');
      expect(controller.hero.name).toEqual('Milesl Bronsonkk'); 
    });
});

这是一个 plunkr: https://plnkr.co/edit/IAs4iYL69E8Nm5uvQDw1?p=preview

关于javascript - Karma 未按预期运行 Angular 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41720079/

相关文章:

javascript - 在页面加载时通过标记名称内联添加一个函数,例如 onmouseover

angularjs - 加载完成后触发回调

download - 在 angularjs 和express.js 之间进行下载

javascript - Angularjs 无法将单选按钮与嵌套范围内的模型绑定(bind)

angularjs - karma-browserify 在单元测试中找不到模块

javascript - 如何在使用 ng-repeat 时验证 AngularJs 中的表单

javascript - 从 WinJS 中的 AppFolder 打开 Iframe 中的本地 HTML 文件

javascript - Angular 1.6,$compileProvider 和测试

mocha.js - 如何在 mocha 记者中获取测试的文件名

javascript - div更新时页面卡住