JavaScript test Tools-karma-jasmine installation and usage _javascript tips

Source: Internet
Author: User
Tags autowatch install node server port

1.Karma Introduction

Karma is Testacular's new name, in 2012 Google Open source testacular,2013 year testacular renamed Karma. Karma is a very mysterious name, said the fate of Buddhism, karma, than Cassandra this name more people guessing!

Karma is a node.js based JavaScript test Execution Process management tool (test Runner). This tool can be used to test all major web browsers, to be integrated into CI (continuous integration) tools, or to work with other code editors. A powerful feature of this test tool is that it can monitor (Watch) file changes and then execute it on its own, displaying the test results through Console.log.

2.Jasmine Introduction

Jasmine (Molly) is a JavaScript BDD (behavior-driven development) testing framework that does not rely on any other JavaScript components. It has clean and clear syntax so you can write out the test code very simply. For JavaScript based development, it is a good test framework choice.

More popular with qunit and Jasmine, if you want to learn more about the difference, please hit the JavaScript Unit test framework Qunit and jasmine comparison.

Cloud Habitat Community Friendship remind you need to pay attention to points: This article in the Data Link, Karma plug-in installation, etc., may need to turn the $ wall before the correct implementation.

Step One: Install Node.js (version: v0.12.4, windows-64)

Karma is run on node.js, so we first have to install Node.js. To https://nodejs.org/download/download the Nodejs version you need for your system, I am downloading the MSI version of the WINDOWS-64 bit.

After downloading, double-click Node-v0.12.4-x64.msi to run and install, this will not repeat, the next step can, of course, it is best to change the directory.

Figure 1 (Choose installation content, default):


Step Two: Install Karma

To run the Node.js command line program: Node.js command prompt:

Figure 2 (in "Start-> All Programs->node.js"):


Figure 3 (we will install to the E:\Karma path):


Enter command to install karma:

Copy Code code as follows:

NPM Install Karma--save-dev

Figure 4 (After Karma installation):


Step three: Install the Karma-jasmine/karma-chrome-launcher plugin

Continue to enter NPM command to install Karma-jasmine, Karma-chrome-launcher plugins:

Copy Code code as follows:

NPM Install Karma-jasmine karma-chrome-launcher--save-dev

Figure 5 (after karma-jasmine, Karma-chrome-launcher installed):


Step Four: Install KARMA-CLI

KARMA-CLI is used to simplify the invocation of karma, and the installation commands are as follows, where-G represents global parameters, which makes it easy to use karma in the future:

Copy Code code as follows:

NPM install-g KARMA-CLI

Figure 6 (after KARMA-CLI installation):

Karma-jasmine Installation Completed:

Figure 7 (after installation, there will be a node_modules directory under the E:\Karma folder that contains the Karma, Karma-jasmine, Karma-chrome-launcher directory that you just installed. Of course, also includes the Jasmine-core directory):

Open karma:

Enter command:

Copy Code code as follows:

Karma Start

Figure 8 (a row of info appears as shown in the figure below and there are no other prompts and actions, because at this point we have not configured the Karma startup parameters.) Karma.conf.js will be added 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, prove that the installation was successful):


Karma+jasmine configuration:

To execute the command init command for configuration:

Karma Init

Figure 10 (all default configuration issues):

Description

1. Test framework: Of course we choose Jasmine

2. Whether to add Require.js plug-ins

3. Choose Browser: We choose Chrome

4. Test file path settings, files can use wildcard matching, such as *.js matching the specified directory of all JS files (the actual operation found that the path is karma.conf.js file relative path, see below I give the actual test configuration and instructions)

5. Files that need to be excluded under the test file path

6. Whether to allow Karma monitoring files, yes means that when the file changes under the test path, Karma will automatically test

My example of testing on a virtual machine:

Figure One (TestFiles and Nodejs in e-packing directory, karma.conf.js in the root directory Nodejs folder):


Here is the complete content of Karma.conf.js:

Karma configuration//generated on Fri May:: gmt+ (China standard Time) module.exports = function (config) {config.set ({// Base path that is 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 value 
  S: ' 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 the test files are in the same directory, we can set BasePath (also relative to the Karma.conf.js file relative path), and then specify files, then the files are basepath directory of the file relative path;

Of course, you can also not set BasePath, direct use relative to the Karma.conf.js file of the path, as in this case, if we keep basepath default is null, the files configuration should be:

Files: [
  '.. /testfiles/jasminetest.js ',
  '. /testfiles/test.js '
 ] 
 
test.js content:
 
function TT () {return
 "abc";
} 
 
Jasminetest.js content:
 
describe ("A suite of basic Functions", function () {
 It ("Test", function () {
  expect (" ABC "). Toequal (TT ());
 });

Start karma:

Karma Start Karma.conf.js

Because the configuration file Karma.conf.js is added this time, karma will follow the parameters specified in the configuration file, because we are configured to test in Chrome, so karma will automatically start the Chrome instance and run the test case:

Figure 12 (Chrome on the left is karma automatically, and the last line in the Node.js Command Prompt window on the right 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 tool, select the Console window, we will see the Jasmine execution Log):


In this case, we change the expected value of the TT method in Jasminetest.js to "ABCD" (actually "abc"):

Describe ("A suite of basic Functions", function () {
 It ("Test", function () {
  expect ("ABCD"). Toequal (TT ());
 } );

Because we set the Autowatch to true in Karma.conf.js:

Autowatch:true

Karma will automatically execute the test case, and as the test case fails in this case, the error message is printed on the screen, and the log information in the Chrome console window needs to be refreshed debug.html the display.

Figure (Karma automatically detects file changes and automates the test case):


Code Coverage:

If you also want to check the code coverage of the test, we can install the Karma-coverage plug-in, the installation command is:

Copy Code code as follows:

NPM Install Karma-coverage

Figure 15 (process of installing karma-coverage):


Modify Karma.conf.js to increase coverage configuration:

Figure 16 (mainly changes the following three configuration nodes, the other configuration content is unchanged):

 Preprocess matching files before serving them to the browser
  //Available preprocessors:https://npmjs.org/browse/k Eyword/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/'
  

The changes are as follows:

Increase the coverage in the reporters
JS file specified in preprocessors

Add the Coveragereporter node, set the coverage report type type to HTML, and enter directory dir to specify the directory you want

At this point the complete karma.conf.js is as follows:

Karma configuration//generated on Fri May 2015 19:30:26-gmt+0800 (China standard Time) module.exports = function (config) {Co Nfig.set ({///base path that is used to resolve all patterns (eg. files, exclude) BasePath: ",//Frameworks to U SE//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 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 value S: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 the SE browsers//Available browser launchers:https://npmjs.org/browse/keyword/karma-launcher browsers: [' Chrome '],//Co
Ntinuous Integration Mode//If True, Karma captures browsers, runs the tests and exits Singlerun:false}); };

To execute a command:

Copy Code code as follows:

Karma Start Karma.conf.js

Figure 17 (after executing the command, in the dir specified in the configuration file Coveragereporter node, we will find the generated coverage report, Karma-coverage also generates a layer of subfolders, corresponding to the browser + version number + Operating system version of the test execution):

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.