To save time and effort when manually running your tests, you can use a test runner. The recipe, Installing Karma, gets you ready to run tests with Karma. This recipe will introduce you to automatically run a Jasmine test with Karma (which you can visit at http://karma-runner.github.io/). You will learn how to set up a basic configuration file and automatically run your tests with Karma.
You can either implement this as an initial step to an existing project, or build upon the basic project created in the first recipe. You can do this as follows:
Karma will need access to the
angular.js
andangular-mocks.js
files, which can be downloaded from https://code.angularjs.org/1.2.28/. Ensure these are included in alib/angular
folder in your project root directory.Copy the
cookbook.js
file from the recipe Creating a basic AngularJS application, into thesrc
directory.Finally, copy the
cookbookSpec.js
file from the Running a simple test using Jasmine recipe in this chapter, into a test directory.
Firstly, you need to create a Karma configuration file named karma.conf.js
with the following code:
module.exports = function(config) { config.set({ frameworks: ['jasmine'], files: [ "lib/angular/angular.js", "lib/angular/angular-mocks.js", "src/cookbook.js", "test/cookbookSpec.js" ], autoWatch: true, browsers: ['Chrome'] }); };
Once this has been created, you can run the following command:
karma start
As a result of this, you should see that Karma launches the Chrome browser and produces the following in the console window:
Karma requires a configuration file for it to run our AngularJS application tests. Let's step through the configuration options:
frameworks
: Framework adaptors that must be installed via thekarma init
process or manually, for examplenpm install karma-jasmine --save-dev
.files
: These are the file patterns specifying applications and test files.autoWatch
: This option watches for changes to applications/test files and re-run tests.browsers
: These are the launchers that must be installed via the karmainit
process or manually, for examplenpm install karma-chrome-launcher --save-dev
.
The angular.js
file is a dependency for angular-mocks.js
, therefore angular.js
must be declared before angular-mocks.js
.
For a more comprehensive list of configuration options, please refer to Karma's configuration file documents at http://karma-runner.github.io/0.12/config/configuration-file.html.
Use a glob pattern for files, as opposed to declaring each file explicitly, by inserting the following code:
files: [ "lib/angular/angular.js", "lib/angular/angular-mocks.js", "src/**/*.js", "test/**/*.js" ]