1.Karma introduction
Karma is the new name of Testacular. In 2012, Google open sourced Testacular. In 2013, Testacular was renamed Karma. Karma is a very mysterious name, which means fate and karma in Buddhism. It is even more unpredictable than a name like Cassandra!
Karma is a JavaScript test execution process management tool (Test Runner) based on Node.js. This tool can be used to test all major web browsers, can also be integrated into CI (Continuous integration) tools, and can also be used with other code editors. A powerful feature of this testing tool is that it can monitor (Watch) file changes, then execute it by itself, and display the test results through console.log.
2.Jasmine introduction
Jasmine is a JavaScript BDD (behavior-driven development) testing framework that does not depend on any other JavaScript components. It has clean and clear syntax, allowing you to easily write test code. It is a good choice of testing framework for JavaScript-based development.
The more popular ones are Qunit and Jasmine. If you want to know the difference between the two in more detail, please click on the comparison of Javascript unit testing frameworks Qunit and Jasmine.
Script House would like to remind everyone that you need to pay attention: the information links appearing in this article, karma plug-in installation, etc. may need to be bypassed before they can be executed correctly.
Step 1: Install Node.JS (version: v0.12.4, windows-64)
Karma runs on Node.js, so we need to install Node.js first. Go to https://nodejs.org/download/ to download the NodeJS version required for your system. I downloaded the windows-64-bit msi version.
After downloading, double-click node-v0.12.4-x64.msi to run and install it. I won’t go into details on this. Just go to the next step. Of course, it is best to change the directory.
Figure 1 (select the installation content, the default is enough):
Step 2: Install Karma
Command line program to run Node.js: Node.js command prompt:
Figure 2 (in "Start->All Programs->Node.js"):
Figure 3 (we will install it under the E:Karma path):
Enter the command to install Karma:
Figure 4 (after Karma is installed):
Step 3: Install the karma-jasmine/karma-chrome-launcher plug-in
Continue to enter the npm command to install the karma-jasmine and karma-chrome-launcher plug-ins:
Figure 5 (after karma-jasmine and karma-chrome-launcher are installed):
Step 4: Install karma-cli
karma-cli is used to simplify the call of karma. The installation command is as follows, where -g represents the global parameter, so that you can use karma very conveniently in the future:
Figure 6 (after karma-cli is installed):
Karma-Jasmine is installed:
Figure 7 (After installation is complete, there will be a node_modules directory under the E:Karma folder, which contains the karma, karma-jasmine, karma-chrome-launcher directories just installed, and of course the jasmine-core directory) :
Turn on Karma:
Enter command:
Figure 8 (After running, a line of INFO information appears as shown in the figure, and there are no other prompts and actions, because we have not configured the startup parameters of karma at this time. We will add karma.conf.js later, so that karma will automatically Start the browser and execute the test case):
Figure 9 (manually open Chrome, enter localhost:9876, if you see this page, it proves that the installation has been successful):
Karma Jasmine Configuration:
Execute the init command to configure:
karma init
Figure 10 (all default configuration issues):
Description:
1. Testing framework: Of course we choose jasmine
2. Whether to add the Require.js plug-in
3. Select browser: We choose Chrome
4. Test the file path setting. Files can be matched using wildcards. For example, *.js matches all js files in the specified directory (in actual operation, it is found that this path is the relative path of the karma.conf.js file. See below for details. Actual test configuration and instructions given)
5. Files that need to be excluded in the test file path
6. Whether to allow Karma to monitor files. Yes means that when the files in the test path change, Karma will automatically test
Example I tested on a virtual machine:
Figure 11 (TestFiles and NodeJS are in the root directory of drive E, karma.conf.js is in the root directory of the folder NodeJS):
The following is the complete content of karma.conf.js:
// Karma configuration // Generated on Fri May :: GMT+ (中国标准时间) module.exports = function(config) { config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) basePath: '../TestFiles', // frameworks to use // available frameworks: https://npmjs.org/browse/keyword/karma-adapter frameworks: ['jasmine'], // list of files / patterns to load in the browser files: [ '*.js' ], // list of files to exclude exclude: [ ], // preprocess matching files before serving them to the browser // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor preprocessors: { }, // test results reporter to use // possible values: 'dots', 'progress' // available reporters: https://npmjs.org/browse/keyword/karma-reporter reporters: ['progress'], // web server port port: , // enable / disable colors in the output (reporters and logs) colors: true, // level of logging // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG logLevel: config.LOG_INFO, // enable / disable watching file and executing tests whenever any file changes autoWatch: true, // start these browsers // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher browsers: ['Chrome'], // Continuous Integration mode // if true, Karma captures browsers, runs the tests and exits singleRun: false }); };
Description:
If all test files are in the same directory, we can set basePath (which is also a relative path relative to the karma.conf.js file), and then specify files. At this time, files are the relative paths of files in the basePath directory;
Of course, you can also not set basePath and directly use the file relative path relative to the karma.conf.js file. In this example, if we keep basePath as empty by default, the files configuration should be:
files: [ '../TestFiles/jasmineTest.js', '../TestFiles/test.js' ] test.js内容: function TT() { return "abc"; } jasmineTest.js内容: describe("A suite of basic functions", function () { it("test", function () { expect("abc").toEqual(TT()); }); });
Start Karma:
karma start karma.conf.js
Since the configuration file karma.conf.js has been added this time, Karma will perform operations according to the parameters specified in the configuration file. Since we are configured to test in Chrome, Karma will automatically start the Chrome instance and Run the test case:
Figure 12 (Chrome on the left is automatically started by Karma, and in the Node.js command prompt window on the right, the last line shows the execution results):
Figure 13 (If we click the debug button in Figure 12, enter debug.html and press F12 to open the developer tools, select the Console window, we will be able to see the execution log of jasmine):
At this time, we change the expected value for calling the TT method in jasmineTest.js to "abcd" (actually "abc"):
describe("A suite of basic functions", function () { it("test", function () { expect("abcd").toEqual(TT()); }); });
由于我们在karma.conf.js中设置了autoWatch为true:
autoWatch: true
Karma将自动执行测试用例,由于本例测试用例未通过,因此在屏幕上打印出了错误信息,Chrome的Console窗口中的日志信息需要刷新debug.html后显示。
图14(Karma自动检测到文件变化并自动重新执行了测试用例):
代码覆盖率:
如果你还想查看测试的代码覆盖率,我们可以安装karma-coverage插件,安装命令为:
图15(安装karma-coverage的过程):
修改karma.conf.js,增加覆盖率的配置:
图16(主要是变动了以下三个配置节点,其他的配置内容不变):
// preprocess matching files before serving them to the browser // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor preprocessors: { '../TestFiles/test.js':'coverage' }, // test results reporter to use // possible values: 'dots', 'progress' // available reporters: https://npmjs.org/browse/keyword/karma-reporter reporters: ['progress','coverage'], coverageReporter:{ type:'html', dir:'../TestFiles/coverage/' },
变动如下:
在reporters中增加coverage
preprocessors中指定js文件
添加coverageReporter节点,将覆盖率报告类型type设置为html,输入目录dir指定到你希望的目录中
此时完整的karma.conf.js如下:
// Karma configuration // Generated on Fri May 29 2015 19:30:26 GMT+0800 (中国标准时间) module.exports = function(config) { config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) basePath: '', // frameworks to use // available frameworks: https://npmjs.org/browse/keyword/karma-adapter frameworks: ['jasmine'], // list of files / patterns to load in the browser files: [ '../TestFiles/jasmineTest.js', '../TestFiles/test.js' ], // list of files to exclude exclude: [ ], // preprocess matching files before serving them to the browser // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor preprocessors: { '../TestFiles/test.js':'coverage' }, // test results reporter to use // possible values: 'dots', 'progress' // available reporters: https://npmjs.org/browse/keyword/karma-reporter reporters: ['progress','coverage'], coverageReporter:{ type:'html', dir:'../TestFiles/coverage/' }, // web server port port: 9876, // enable / disable colors in the output (reporters and logs) colors: true, // level of logging // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG logLevel: config.LOG_INFO, // enable / disable watching file and executing tests whenever any file changes autoWatch: true, // start these browsers // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher browsers: ['Chrome'], // Continuous Integration mode // if true, Karma captures browsers, runs the tests and exits singleRun: false }); };
执行命令:
图17(执行命令后,在配置文件coverageReporter节点中指定的dir中,我们将找到生成的覆盖率报告,karma-coverage还生成了一层子文件夹,对应于执行测试的浏览器+版本号+操作系统版本):