Configure unit tests on local machine
https://jasmine.github.io/
https://karma-runner.github.io/latest/index.html
Write unit tests
For writing unit tests we will use the Jasmine framework.
- Initialize NodeJS project with
npm init
and install jasmine:
npm init
npm install --save-dev jasmine
- Unit tests are located in
*.spec.js
files. Create spec file with unit tests forsum.js
, in this tutorial we will test thesum
function only:
js/sum.spec.js
describe('Sample project', () => {
it('sum should return 3', () => {
const result = sum(1, 2);
expect(result).toBe(3);
});
it('sum should return 0', () => {
const result = sum(1, -1);
expect(result).toBe(0);
});
});
- Install test runner named Karma with Chrome launcher and Jasmin plugin:
npm install --save-dev karma karma-jasmine karma-chrome-launcher
- Create karma configuration file:
karma.conf.js
module.exports = config => {
config.set({
basePath: './js',
frameworks: ['jasmine'],
files: [
'**/*.js'
],
exclude: [
'main.js'
],
preprocessors: {},
reporters: ['progress'],
port: 9876,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false,
concurrency: Infinity
});
};
- Add test command into
package.json
file:
"scripts": {
"test": "karma start karma.conf.js"
}
- Run tests:
npm run test