PhantomJS is a headless browser for the tests to interact with.
Install Karma and RequireJS
2. Setup the Config file
..and when prompted, select:
- Testing Framework: Jasmine
- Require.js: yes
- Browser: PhantomJS
- Pattern of source files *:
- Patterns to exclude:
..then skip through the rest
* this is how Karma finds the JS files to load for testing
This will then have generated a configuration file called ‘karma.conf.js’ with the necessary settings to run Karma - if anything you selected was wrong, you can always edit this file to correct it.
3. Create test-main.js
Create a ‘test-main.js’ (or whatever you named this file) with the following:
4. Write Unit Tests
Write your Unit tests according to the pattern that you set Karma to search for the files in karma.config.js and the pattern to load test files you set at the top of test-main.js.
I write a test file for each JS file by using the original JS filename with a suffix of ‘Test.js’ and store them in a ‘tests’ directory, for example:
Within these test files you can require the modules that you wish to test and use the Testing Framework that you selected to make assertions. The default for Karma is Jasmine - you can learn the syntax for this at: pivotal.github.io/jasmine/
5. Run Karma
Run the following to start Karma:
If you left
autoWatch: true, in the ‘karma.conf.js’ file, Karma with continue
to listen for changes to your files and return the outcomes as soon as you save
a file, otherwise you will have to either manually run karma start for every
change you make or use a task runner like Grunt to watch for changes.