Install and use Karma-Jasmine for automated testing

Keywords: npm Javascript Web Server Windows

Note: Data links, karma plug-in installation, etc. that appear in this article may require a $wall flip to perform correctly.

Jasmine is a Javascript testing tool that runs Jasmine on Karma to automate Javascript testing, generate coverage reports, and so on.This article doesn't contain any details about Jasmine's use. I'll write an introductory article about Jasmine these days, which interested friends can check out when they see it.

Step 1: Install Node.JS

Karma runs on Node.js, so we'll install Node.js first.To https://nodejs.org/download/ Download the required version of NodeJS for your system. I am downloading the msi version of windows-64 bit.

After downloading, double-click the node-v0.12.4-x64.msi to run and install, which is not to be overlooked. Continue to the next step, preferably changing the directory.

Figure 1 (Choose what to install, default):

Step 2: Install Karma

Run the Node.js command-line program: Node.js command prompt:

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

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


Enter a command to install Karma:

npm install karma --save-dev

Figure 4 (after Karma is installed):


Step 3: Install the karma-jasmine/karma-chrome-launcher plug-in

Continue typing the npm command to install the karma-jasmine, karma-chrome-launcher plug-ins:

npm install karma-jasmine karma-chrome-launcher --save-dev

Figure 5 (after installation of karma-jasmine and karma-chrome-launcher):


Step 4: Install karma-cli

karma-cli is used to simplify the call to karma. The installation command is as follows, where -g represents the global parameter, which makes it very convenient to use karma in the future:

npm install -g karma-cli

Figure 6 (after karma-cli installation):


Karma-Jasmine is installed:

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 directories and, of course, jasmine-core directories you just installed):


Turn on Karma:

Enter command:

karma start

Figure 8 (A line of INFO information appears after running as shown in the figure, with no other prompts or actions, as karma's startup parameters are not configured at this time.karma.conf.js will be added later so that karma will automatically launch the browser and execute the test case:


Figure 9 (Open Chrome manually, enter localhost:9876, and if you see this page, prove that the installation was successful):


Karma+Jasmine configuration:

Execute the command init command to configure:

karma init

Figure 10 (all default configuration issues):


Explain:

1. Test framework: of course we chose jasmine

2. Add Require.js plug-in

3. Choose Browser: We choose Chrome

4. Test file path settings, files can be matched using wildcards, such as *.js to match all JS files in the specified directory (found in practice to be relative paths to karma.conf.js files, see the actual test configuration and instructions given below)

5. Files to be excluded under test file path

6. Whether Karma is allowed to monitor files, yes indicates that Karma will automatically test when the files under the test path change

Examples I tested on virtual machines:

Figure 11 (TestFiles and NodeJS are in the root directory of drive E and karma.conf.js is in the root directory of folder NodeJS):


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

 1 // Karma configuration
 2 // Generated on Fri May 29 2015 19:30:26 GMT+0800 (China Standard Time)
 3 
 4 module.exports = function(config) {
 5   config.set({
 6 
 7     // base path that will be used to resolve all patterns (eg. files, exclude)
 8     basePath: '../TestFiles',
 9 
10 
11     // frameworks to use
12     // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
13     frameworks: ['jasmine'],
14 
15 
16     // list of files / patterns to load in the browser
17     files: [
18       '*.js'
19     ],
20 
21 
22     // list of files to exclude
23     exclude: [
24     ],
25 
26 
27     // preprocess matching files before serving them to the browser
28     // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
29     preprocessors: {
30     },
31 
32 
33     // test results reporter to use
34     // possible values: 'dots', 'progress'
35     // available reporters: https://npmjs.org/browse/keyword/karma-reporter
36     reporters: ['progress'],
37 
38 
39     // web server port
40     port: 9876,
41 
42 
43     // enable / disable colors in the output (reporters and logs)
44     colors: true,
45 
46 
47     // level of logging
48     // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
49     logLevel: config.LOG_INFO,
50 
51 
52     // enable / disable watching file and executing tests whenever any file changes
53     autoWatch: true,
54 
55 
56     // start these browsers
57     // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
58     browsers: ['Chrome'],
59 
60 
61     // Continuous Integration mode
62     // if true, Karma captures browsers, runs the tests and exits
63     singleRun: false
64   });
65 };

Explain:

If all the test files are in the same directory, we can set the basePath (which is also the relative path to the karma.conf.js file) and then specify the files, in which case the files are the relative path to the files in the basePath directory;

You can also use the file relative path relative to the karma.conf.js file without setting basePath, for example, if we leave basePath blank by default, the files configuration should be:

files: [
      '../TestFiles/jasmineTest.js',
      '../TestFiles/test.js'
    ]

test.js content:

function TT() {
    return "abc";
}

Contents of 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 was added this time, Karma will follow the parameters specified in the configuration file. Since we are configuring to test in Chrome, Karma will automatically start the Chrome instance and run the test case:

Figure 12 (The 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 results):


Figure 13 (If we click the debug button in Figure 12, enter debug.html, press F12 to open the developer tool, select the Console window, and we will see the execution log of jasmine):


If so, we will change the expected value in jasmineTest.js for calling TT methods to "abcd" (actually "abc"):

describe("A suite of basic functions", function () {
    it("test", function () {
        expect("abcd").toEqual(TT());
    });
});

Since we set autoWatch to true in karma.conf.js:

autoWatch: true

Karma will automatically execute the test case, and since the test case failed, an error message is printed on the screen, and the log information in Chrome's Console window needs to be refreshed to debug.html.

Figure 14 (Karma automatically detects file changes and automatically re-executes test cases):


Code coverage:

If you also want to see the code coverage of the tests, we can install the karma-coverage plug-in with the following commands:

npm install karma-coverage

Figure 15 (Installation of karma-coverage):


Modify karma.conf.js to increase coverage configuration:

Figure 16 (mainly the following three configuration nodes have been changed, while the rest remain unchanged):

 1     // preprocess matching files before serving them to the browser
 2     // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
 3     preprocessors: {
 4         '../TestFiles/test.js':'coverage'
 5     },
 6 
 7 
 8     // test results reporter to use
 9     // possible values: 'dots', 'progress'
10     // available reporters: https://npmjs.org/browse/keyword/karma-reporter
11     reporters: ['progress','coverage'],
12     
13     coverageReporter:{
14         type:'html',
15         dir:'../TestFiles/coverage/'
16     },

The changes are as follows:

  • Increase coverage in reports
  • Specify js file in preprocessors
  • Add a coverage Reporter node, set the coverage report type to html, and specify the input directory dir to the directory you want

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

 1 // Karma configuration
 2 // Generated on Fri May 29 2015 19:30:26 GMT+0800 (China Standard Time)
 3 
 4 module.exports = function(config) {
 5   config.set({
 6 
 7     // base path that will be used to resolve all patterns (eg. files, exclude)
 8     basePath: '',
 9 
10 
11     // frameworks to use
12     // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
13     frameworks: ['jasmine'],
14 
15 
16     // list of files / patterns to load in the browser
17     files: [
18       '../TestFiles/jasmineTest.js',
19       '../TestFiles/test.js'
20     ],
21 
22 
23     // list of files to exclude
24     exclude: [
25     ],
26 
27 
28     // preprocess matching files before serving them to the browser
29     // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
30     preprocessors: {
31         '../TestFiles/test.js':'coverage'
32     },
33 
34 
35     // test results reporter to use
36     // possible values: 'dots', 'progress'
37     // available reporters: https://npmjs.org/browse/keyword/karma-reporter
38     reporters: ['progress','coverage'],
39     
40     coverageReporter:{
41         type:'html',
42         dir:'../TestFiles/coverage/'
43     },
44 
45 
46     // web server port
47     port: 9876,
48 
49 
50     // enable / disable colors in the output (reporters and logs)
51     colors: true,
52 
53 
54     // level of logging
55     // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
56     logLevel: config.LOG_INFO,
57 
58 
59     // enable / disable watching file and executing tests whenever any file changes
60     autoWatch: true,
61 
62 
63     // start these browsers
64     // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
65     browsers: ['Chrome'],
66 
67 
68     // Continuous Integration mode
69     // if true, Karma captures browsers, runs the tests and exits
70     singleRun: false
71   });
72 };
View Code

Execute command:

karma start karma.conf.js

Figure 17 (After executing the command, in the dir specified in the profile coverage Reporter node, we will find the generated coverage report, and karma-coverage also generates a subfolder corresponding to the browser + version number + operating system version in which the test was executed):


Posted by IwnfuM on Wed, 17 Jul 2019 11:10:48 -0700