Karma单元测试用例未执行

时间:2016-01-11 10:12:55

标签: angularjs unit-testing controller karma-runner

Karma单元测试用例未执行。当我运行karma start my.conf.js命令时没有错误。 DEBUG控制台中没有显示任何内容。任何人都可以告诉可能是什么问题? 这是我的控制器文件:

define('',['angular', 'moment', '../module'], function (ng, moment) {
  'use strict';

  ng
  .module('PatientRecord.controllers')
  .controller('PatientRecordController', ["$scope", "PatientRecordService", 'globalConfig',
      function ($scope, PatientRecordService, globalConfig) {
      $scope.addSubmitted = false;
      $scope.updateSubmitted = false;
      $scope.shareSubmitted = false;
      $scope.deleteSubmitted = false;
      $scope.patientRecords = [];
      $scope.modalRecord = {};
      $scope.sharedDoctors = [];
      $scope.potentialDoctors = [];
      $scope.medicalRecordsList = false;
      $scope.disableShareButton = true;
      $scope.validation = {
                              success:{
                                status:false,
                                message:""
                              },
                              error:{
                                status:false,
                                message:""
                              }
                          };

      $scope.file = {};
      var patientRecordService = new PatientRecordService();

      $scope.getRecord = function () {
        $scope.patientRecords.length = 0;
        patientRecordService.getRecords().then(function (response) {
          $scope.patientRecords = response;
          if ($scope.patientRecords.length) {
            $scope.medicalRecordsList = true;
          }
        });
        $('body').tooltip({
            selector: '.action-icon'
        });
      };

    $scope.addPatientRecord = function ($event) {
        $scope.addSubmitted =true;
        $scope.patientRecord.shared = [];
        $scope.patientRecord.file = $scope.addRecordFileUpload;
        patientRecordService.addPatientrecorddata($scope.patientRecord)
        .then(function (response) {
            $scope.addSubmitted = false;
            clearAddRecordFields();
            $("#add-record").modal("hide");
         $scope.getRecord();

          if(response){
            $scope.validation.success.status = true;
            $scope.validation.success.message = "Record added successfully";
            $scope.addForm.$setPristine();
            $scope.addForm.addRecordFileUpload.$error.required = true;
            $scope.patientRecord.medicalRecordTypeId ="";
            $scope.addRecordFileUpload = "";
          }else{
            $scope.validation.error.status = true;
            $scope.validation.error.message = "Confirmation is unsuccessful. Please try again";
          }
        });

      };

    $scope.closeAddDialog = function () {
      clearAddRecordFields();
      $("#add-record").modal("hide");
    };

    var clearAddRecordFields = function(){
      $scope.patientRecord.name = "";
      $scope.patientRecord.dateOfRecord = "";
      $scope.patientRecord.comments = "";
      $scope.patientRecord.medicalRecordType = "";
      $scope.patientRecord.addRecordFileName = "";

      $("#patientRecord_name").val("");
      $("#dateOfRecord").val("");
      $("#patientRecord_comments").val("");
      $("#medicalRecordType").val("");
      $("#addRecordFileName").html("");
    }





    var dispalyFileName = function (FileControlId, placeholderId) {
        if ($scope.currntFileObject) {
          $('#' + placeholderId).empty().html($scope.currntFileObject.name);
        }
    };


    $scope.openupdateModal = function (record) {
      $scope.modalRecord =  _.clone(record);
        var dateOfRecord = moment($scope.modalRecord.date_of_record).format("DD MMM, YYYY");
        $scope.modalRecord.date_of_record = dateOfRecord;
        $scope.disableShareButton = true;
        $("#updateRecordFileName").html("");
        //Get Shared Doctors Data
        patientRecordService.getSharedDoctorsByRecordId(record.id).then(function (response) {
        $scope.sharedDoctors = _.where(response, { isShared: true })
        $scope.potentialDoctors = _.where(response, { isShared: false })
        });
    };

    $scope.updatePatientrecord = function (index) {
        $scope.updateSubmitted = true;
        $scope.modalRecord.medicalRecordTypeId = $("#update_recordtype").val();
        $scope.modalRecord.file = $scope.updateRecordFileUpload;
        patientRecordService.updatePatientdata($scope.modalRecord)
        .then(function (response) {
            $scope.updateSubmitted = false;
            $scope.getRecord();
         });
   };

   angular.element("#selectDoctorToShare_foreditDialog").change(function () {
        var selectedDoctorId = $("#selectDoctorToShare_foreditDialog").val();
              $scope.$apply(function () {
                  if (selectedDoctorId != 0) {
                      $scope.disableShareButton = false;
                  } else {
                      $scope.disableShareButton = true;
                  }
                });
    });




    $scope.closeUpdateDialog = function () {
        $("#patientRecord_name").val("");
        $("#datetimepicker1").val("");
        $("#patientRecord_comments").val("");
        $("#medicalRecordType").val("");
        $("#addRecordFileName").html("");
        $("#modify-record").modal("hide");
        $scope.getRecord();
    };

    $scope.openShareDialog = function (data) {
          $scope.modalRecord = data;
          $scope.disableShareButton = true;
          patientRecordService.getSharedDoctorsByRecordId(data.id)
              .then(function (response) {
                  $scope.sharedDoctors = _.where(response, { isShared: true })
                  $scope.potentialDoctors = _.where(response, { isShared: false })
                });
      }

      $scope.sharePatientRecord = function(doctorDropdownId,recordId){
          $scope.shareSubmitted  = true;
       var selectedDoctorId = $("#"+doctorDropdownId).val();
       patientRecordService.sharePatientData(recordId, selectedDoctorId).then(function(response){
           $scope.shareSubmitted  = false;
        if(response){
          if(doctorDropdownId == "selectDoctorToShare_forShareDialog") {
            $("#share-record").modal("hide");
          }
          alert("Record shared successfully");


          patientRecordService.getSharedDoctorsByRecordId($scope.modalRecord.id)
          .then(function(response) {
            $scope.sharedDoctors = _.where(response, {isShared: true})
            $scope.potentialDoctors = _.where(response, {isShared: false})
          });
         $scope.disableShareButton = true;
       } else {
        alert("Something went wrong! Try again")
      }
      });
     };

      angular.element("#selectDoctorToShare_forShareDialog").change(function () {
      var selectedDoctorId = $("#selectDoctorToShare_forShareDialog").val();
              $scope.$apply(function () {
                  if (selectedDoctorId != 0) {
                      $scope.disableShareButton = false;
                  } else {
                      $scope.disableShareButton = true;
                  }
              });
      });


     $scope.OpenDeleteModal = function (data, index) {
        $scope.modalRecord = data;
        $scope.index = index;
        $("#delete-record-modal").modal("show");
    }

    $scope.deletePatientrecord = function (data, index) {
      $scope.deleteSubmitted  = true;
        var patientRecordService = new PatientRecordService();
      patientRecordService.deletePatientdata(data.id).then(function (response) {
          $scope.deleteSubmitted  = false;
        $("#delete-record-modal").modal("hide");
        $scope.getRecord();
        if(response){
          $scope.validation.success.status = true;
          $scope.validation.success.message = "Record deleted successfully";
        }else{
          $scope.validation.error.status = true;
          $scope.validation.error.message = "Record could not be deleted";
        }

      });
    };
    $scope.getRecord();
  }
  ]);

});

控制器的测试文件:

// Testing PatientRecordController
    define('',['angular', 'moment', '../module'], function (ng, moment) {
    describe("Controller: PatientRecordController", function() {
        // load the controller's module
      beforeEach(module('PatientRecord.controllers'));

      var PatientRecordController,
      scope;

    // Initialize the controller and a mock scope
      beforeEach(inject(function ($controller, $rootScope) {
          scope = $rootScope.$new();
          PatientRecordController = $controller('PatientRecordController', {
                                          '$scope': scope
                                    });
      }));

      // Check if controller is defined
      it("should have a PatientRecordController as controller", function() {
        expect(PatientRecord.controllers.PatientRecordController).toBeDefined();
        console.log('controllers defined');
      });
    });
    });

my.conf.js文件:

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

    // base path, that will be used to resolve files and exclude
    basePath: '',


    // frameworks to use
    frameworks: ['jasmine','requirejs'],


    // list of files / patterns to load in the browser
    files: [

      'app/modules/PatientRecord/controllers/PatientRecordController.js'

    ],


    // list of files to exclude
    exclude: [

    ],


    // test results reporter to use
    // possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
    reporters: ['progress','coverage','html'],

    htmlReporter: {
        outputFile: 'tests/units.html'
    },

    preprocessors: {
      // source files, that you wanna generate coverage for
      // do not include tests or libraries
      // (these files will be instrumented by Istanbul)
      'src/**/*.js': ['coverage']
    },

    // optionally, configure the reporter
    coverageReporter: {
      type : 'html',
      dir : 'coverage/',
      file:'coverageds.txt'
    },

    // 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, currently available:
    // - Chrome
    // - ChromeCanary
    // - Firefox
    // - Opera (has to be installed with `npm install karma-opera-launcher`)
    // - Safari (only Mac; has to be installed with `npm install karma-safari-launcher`)
    // - PhantomJS
    // - IE (only Windows; has to be installed with `npm install karma-ie-launcher`)
    browsers: ['Chrome'],


    // If browser does not capture in given timeout [ms], kill it
    captureTimeout: 60000,


    // Continuous Integration mode
    // if true, it capture browsers, run tests and exit
    singleRun: false
  });
};

1 个答案:

答案 0 :(得分:1)

问题出在您的业力配置文件的files部分。首先,如果您使用任何应用程序,则需要包含所有应用程序的库依赖项(如Jquery,Angular,Bootstrap)。其次,您需要包含您正在测试的文件。首先包括应用程序的初始化文件(app.js)和子模块。最后,您需要自己包含实际测试。包含事物的顺序很重要。很多人为此使用RequireJS,但我认为除非你有一个庞大而复杂的项目,否则这是完全必要的。