Karma is an open source JavaScript command-line tool, which is used to spawn a web server to load an application's source code and execute the test. We can configure Karma to run from different browsers. Karma is a command-line tool and will show the results of the application on the command line when the application runs in the browser. Karma is a Node.js application that can be installed through the npm package manager using the following code:
$ npm install --save-dev karma We used the following command to execute the karma $ karma start karma.conf.js We needs to test the following AngularJS's controller var app = angular.module('myApp', []) app.controller('ctrlMain', function($scope) { $scope.name = "Mohammad Majid"; $scope.sayHello = function() { $scope.greeting = "Hello " + $scope.name; } });
First, we need to create an actual test file that will be used in the Jasmine framework, since it works well with Karma. Add the following code to the test file:
describe('Unit: ctrlMain', function() { // Load the module with MainController beforeEach(module('myApp')); var ctrl, scope; // inject the $controller and $rootScope services // in the beforeEach block beforeEach(inject(function($controller, $rootScope) { // Create a new scope that's a child of the $rootScope scope = $rootScope.$new(); // Create the controller ctrl = $controller('ctrlMain', { $scope: scope }); })); });
The preceding code will be used to test the function sayHello()
method simply prepends the $scope.name
variable to a $scope.greeting
variable.