使用 Jasmine 和 Karma / AngularJS 项目进行单元测试

Unit testing using Jasmine and Karma / AngularJS project

我正在使用 AngularJS 和 Jamsine 编写测试用例。使用 AngularJS 和 UI 使用 IONIC 框架开发移动应用程序。所以我从我的 spec.js 调用控制器函数之一进行测试。同时,我收到类似错误。

错误:意外请求:GET ./partials/main.html

没有更多的请求被排除

这是我的邮件 html 文件。在 main.html 文件中,我们正在加载应用程序的所有其他状态。

而且我已经在 spec.js 中注入了 html。请参阅下面的代码。

beforeEach(inject(function ($rootScope, $controller, $q,$injector) {

        $httpBackend = $injector.get('$httpBackend');
        $httpBackend.whenGET('./partials/main.html').respond(200, '');

}));

我仍然无法解决错误。我可以在 'spec.js' 中添加那些 html 文件吗?或任何其他解决方案?请帮我。我是 Karma 和 Jasmine 的新生。

提前致谢。

像这样将代码更改为 expectGET 代替 whenGET

beforeEach(inject(function ($rootScope, $controller, $q,$injector) {

    $httpBackend = $injector.get('$httpBackend');
    $httpBackend.expectGET('./partials/main.html').respond(200);

}));

是的,凯沙夫。请看下面的代码:

下面是我的 karma.conf.js 文件。这是我需要测试的所有添加文件。此外,我还添加了一些用于生成报告和代码覆盖率的插件。

module.exports = function(config) {
  config.set({
     basePath: '',
    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine'],
    plugins: [
      'karma-jasmine',
      'karma-coverage',
      'karma-chrome-launcher',
      'karma-html-reporter',
      'karma-ng-html2js-preprocessor'
],

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

    'my_dir_path/www/js/libs/angular.js',
    'my_dir_path/www/js/libs/angular-mocks.js',
    'my_dir_path/www/js/libs/ionic.js',
    'my_dir_path/www/js/libs/angular.min.js',
    'my_dir_path/www/js/libs/angular-route.js',
    'my_dir_path/www/js/libs/angular-sanitize.js',
    'my_dir_path/www/js/libs/angular-animate.js',
    'my_dir_path/www/js/libs/angular-touch.min.js',
    'my_dir_path/www/js/libs/angular-ui-router.js',
    'my_dir_path/www/js/libs/ionic-angular.js',
    'my_dir_path/www/js/libs/http-auth-interceptor.js',
    'my_dir_path/www/js/libs/ng-map.min.js',
    'my_dir_path/www/js/index.js',
    'my_dir_path/www/js/app.js',
    'my_dir_path/www/js/controllers.js',
    'my_dir_path/www/js/services.js',
    'my_dir_path/www/js/startSpec.js',
    '*.html'
],

// 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: {
  //'**/*.html': ['angular-templating-html2js']
  "my_dir_path/www/partials/*.html": ["ng-html2js"]
},

ngHtml2JsPreprocessor: {
    // If your build process changes the path to your templates,
    // use stripPrefix and prependPrefix to adjust it.
    //stripPrefix: "source/path/to/templates/.*/",
    //prependPrefix: "web/path/to/templates/",
    stripPrefix:"my_dir_path/www/",
    // the name of the Angular module to create
    moduleName: 'partials'
},

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

// the default configuration
/* htmlReporter: {
  outputDir: 'karma_html',
  templatePath: 'node_modules/karma-html-reporter/jasmine_template.html'
}, */

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

这是我的 spec.js 文件。在这里,我正在为控制器编写单元测试用例。在此规范中,调用函数“$scope.onClickResetForgot()”(在控制器中)用于测试控制器代码。在控制器中,我还调用了一个 HTTP 服务。 HTTP 调用后,我们无法回复为什么我们通过 $scope.$digest().

手动更新范围
   'use strict';

    describe('loginController', function () {
        var $scope,$controller,$httpBackend, AuthenticationService, def, respData = {data : {Success:true,ErrorMsg:""}};

        beforeEach(inject(function ($rootScope, $controller, $q,$injector) {

            $httpBackend = $injector.get('$httpBackend');
            $httpBackend.expectGET('./partials/main.html').respond(200);

            AuthenticationService = {
              forgotPassword: function (data) {
                console.log(data);  
                def = $q.defer();
                return def.promise;
              }
            };

            spyOn(AuthenticationService, 'forgotPassword').and.callThrough();
            $scope = $rootScope.$new();
            $controller = $controller('loginController', {
            '$scope': $scope,
            AuthenticationService : AuthenticationService    
            });
        }));

        it("Verifying login credentials, device token and device id." , function() {

            $scope.Reset.Email = "harish.patidar@gmail.com";
            $scope.onClickResetForgot();
            def.resolve(respData);
            // Update response to controller. So we need to call below line manually. 
            $scope.$digest();
            expect(AuthenticationService.forgotPassword).toHaveBeenCalled();
            $httpBackend.flush();   
        })
    });

});

这是我在 controller.js 中的控制器。

    .controller('loginController', ['$rootScope', '$scope', '$http', '$state', 'AuthenticationService', '$ionicPopup', function($rootScope, $scope, $http, $state, AuthenticationService,$ionicPopup) {

    $scope.onClickResetForgot =function(type) {

      console.log($scope.Reset.Email);
      $scope.forgotMessage = "";
      $rootScope.message = "";
      AuthenticationService.forgotPassword({"Email": $scope.Reset.Email}).then(function (resp) {

            var forgotPasswordPopup = $ionicPopup.alert({
                  title: "Forgot Password",
                  template: "An email has been sent to '"+$scope.Reset.Email+"' with instructions for recovering your AlertSense credentials"
              });

            forgotPasswordPopup.then(function(res) {
                $scope.onCancelForgot();
            });


      });
    }

}])

因此,在将范围更新为控制器之后,出现了上述错误。如果您需要更多信息,请告诉我。