Home Web Front-end JS Tutorial Detailed explanation of the installation and use of JavaScript testing tool Karma-Jasmine_javascript skills

Detailed explanation of the installation and use of JavaScript testing tool Karma-Jasmine_javascript skills

May 16, 2016 pm 03:28 PM

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:

Copy code The code is as follows:

npm install karma --save-dev

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:

Copy code The code is as follows:

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

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:

Copy code The code is as follows:

npm install -g karma-cli

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:

Copy code The code is as follows:

karma start

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
 });
 };
Copy after login

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());
 });
}); 
Copy after login

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());
 });
}); 
Copy after login

由于我们在karma.conf.js中设置了autoWatch为true:

autoWatch: true

Karma将自动执行测试用例,由于本例测试用例未通过,因此在屏幕上打印出了错误信息,Chrome的Console窗口中的日志信息需要刷新debug.html后显示。

图14(Karma自动检测到文件变化并自动重新执行了测试用例):


代码覆盖率:

如果你还想查看测试的代码覆盖率,我们可以安装karma-coverage插件,安装命令为:

复制代码 代码如下:

npm install 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/'
  }, 
Copy after login

变动如下:

在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
 });
};
Copy after login

执行命令:

复制代码 代码如下:

karma start karma.conf.js

图17(执行命令后,在配置文件coverageReporter节点中指定的dir中,我们将找到生成的覆盖率报告,karma-coverage还生成了一层子文件夹,对应于执行测试的浏览器+版本号+操作系统版本):

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

Can PowerPoint run JavaScript? Can PowerPoint run JavaScript? Apr 01, 2025 pm 05:17 PM

JavaScript can be run in PowerPoint, and can be implemented by calling external JavaScript files or embedding HTML files through VBA. 1. To use VBA to call JavaScript files, you need to enable macros and have VBA programming knowledge. 2. Embed HTML files containing JavaScript, which are simple and easy to use but are subject to security restrictions. Advantages include extended functions and flexibility, while disadvantages involve security, compatibility and complexity. In practice, attention should be paid to security, compatibility, performance and user experience.

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

See all articles