Nodejs+karma+WebStorm 进行js单元测试

2018-07-16
JavaScript
4582

安装Node.js

Windows系统直接在官网下载安装包,安装。安装好之后也不用设置环境变量,npm(Node.js package manager)也自动安装,npm默认安装路径为:C:\Users\mobvoi\AppData\Roaming\npm 安装完成之后,输入以下命令,查看版本信息。

node -v
npm -v

安装karma

Karma是一个驱动测试的Runner。也就是说,karma为测试框架准备运行环境

npm install -g karma

在任意目录下输入如下命令,全局安装karma。

WebStorm配置karma

打开WebStorm,选择File->Settings->Tools->External Tools karma-setting

创建karma.conf.js配置文件

打开webstorm左下角的terminal(控制台),cd 到当前目录,输入karma init初始化karma.conf.js配置文件.

写测试文件

测试文件一律放在此目录下的test文件夹中,启动测试时,程序会自动将test文件夹中的文件当做测试文件。

开启服务

karma start

实例代码

文件结构

src

main.js

test

mainSpec.js

karma.conf.js

karma.conf.js

// Karma configuration
// Generated on Thu Aug 28 2014 22:06:47 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: {

        'src/*.js',
        'test/*Spec.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: 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
  });
};

main.js

function add(a,b){
    return a + b;
}

mainSpec.js

describe('test add function',function(){
    it('test the return statement', function(){
        spec(add(1,2).toEqual(3));   // return true
    })
})

这里是karma的官方文档,写的很详细:

http://karma-runner.github.io/1.0/index.html