Unit Tests Back
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?
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?
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);
});
});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']
});
};