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

时间:2015-01-19 06:12:13

标签: angularjs karma-runner karma-jasmine

我正在使用AngularJS和Jamsine编写测试用例。使用AngularJS处理移动应用程序,使用IONIC框架处理UI。所以我从我的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的新人。

提前致谢。

2 个答案:

答案 0 :(得分:1)

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

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

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

}));

答案 1 :(得分:0)

是Keshav。请参阅以下代码:

以下是我的 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();
            });


      });
    }

}])

所以在将范围更新到控制器之后,我收到了如上所述的错误。如果您需要更多信息,请与我们联系。