Да Кешав. См. Ниже код:
Ниже приведено мое 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 = "[email protected]";
$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();
})
});
});
И это мой контроллер в контроллере.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();
});
});
}
}])
Так что после обновления области до контроллера, я получаю ошибку, как упоминалось выше. Пожалуйста, дайте мне знать, если вам нужна дополнительная информация.
Не могли бы вы подробнее рассказать/указать пример кода конфигурации приложения и модуля (контроллера в вашем случае) и тестового файла? Это вряд ли описывает ваш вопрос. –
Пожалуйста, см. Ниже моего сообщения. –