Unit Tests Back
1. Introduction
Unit tests should be a large topic in the computer science when taking about tests during developing. However, this article is only focusing on how to do unit tests in JavaScript, and how we can use this tool to easily test our code. As there are so many tools for unit tests, here I want to document them, which can be seen in my developing work.
So, how to write unit tests, and run it?
2. Frameworks
When it comes to frameworks of unit tests, JavaScript developers usually make a decision among following:
- QUnit
- Jasmine
- Mocha
So what is the differences between them?
QUnit | Jasmine | Mocha | |
---|---|---|---|
Features |
|
|
|
Methods |
|
|
|
Summary |
It's easy to use, because you just need to include two files before running tests. |
It's easier to use, because all things has been wrapped in a package. |
It's flexible but not easy to use, as you have to choose assertion framework, like Chai, which is the most popular alternative. |
As shown in the table above, we can apparently know the main different features among theses three frameworks, and different methods we may use to create test cases. Then, how to create cases explicitly?
For QUnit, we can code like this snippet:
/** test.spec.js */
test('case', function () {
ok(1 == '1', 'Passed!');
});
As for Jasmine:
/** test.spec.js */
describe('case1', function () {
it('should not be equal', function () {
expect(1).not.toEqual('1');
});
});
/** ignore the following thest */
xdescribe('case2', function () {
it('should be equal', function () {
expect(1).toEqual('1');
})
});
When it comes to Mocha, it's similar to Jasmine:
/** test.spec.js */
describe('case', function () {
it('should not be equal', function () {
expect(1).to.equal(1);
});
});
3. Karma
When learning AngularJS (Angular 1.x), we may know that the official tutorial of AngularJS has adopted Karma to run unit tests. If we also want to use Karma, we may have to set up a configuration file firstly, named karma.conf.js
.
module.exports = function (config) {
config.set({
/** the root path of your application */
basePath: '.',
/** unit tests files */
files: [
'**/*.spec.js'
],
frameworks: ['jasmine'],
browsers: ['Chrome'],
plugins: [
'karma-chrome-launcher',
'karma-jasmine'
]
/** run a server to watch any change of unit tests files */
autoWatch: false,
/** only run tests once */
singleRun: true,
/** we need mocha to do unit tests */
repoters: ['mocha']
});
};