常用的前端自动化测试工具介绍 —— Karma

简介: 常用的前端自动化测试工具介绍 —— Karma

在开发的过程中,除了代码本身,测试也是重要的一环。大体来说,测试分为以下几种类型:

  • 单元测试
  • 功能测试
  • 性能测试
  • 安全测试

对于普通开发者而言,单元测试和功能测试是最常见的两种测试方式,本系列文章要介绍的几个工具是针对这两个方面的。

单元测试是对某一块独立的业务模块进行测试,可以是一个小功能,甚至一个函数。在前端开发中,我们可以选用 Karma 进行代码的单元测试,这个工具十分强大,它集成了像 Jasmine(基于 BDD 的测试框架),PhantomJS(无界面的浏览器) 这些测试套件。还有一些其他有用的功能,比如生成代码覆盖率的报告等。

本文只介绍 Karma 的基本使用。

单元测试工具 Karma

要使用 Karma 对代码进行单元测试,首先需要安装一系列的相关插件。我们来新建一个名为 myKarmDemo 的目录,并安装相关的插件:

image.png

接下来对我们的工程进行初始化:

image.png

之后会弹出一些选项,其中包含了一些初始化的配置工作,使用上下方向键可以在配置项之间进行切换。我这里选择使用 Jasmine 测试框架,使用 PhantomJS 无界面浏览器,整体的配置选项如下:

myKarmDemo karma init
Which testing framework do you want to use ?
Press tab to list possible options. Enter to move to the next question.
> jasmine
Do you want to use Require.js ?
This will add Require.js plugin.
Press tab to list possible options. Enter to move to the next question.
> no
Do you want to capture any browsers automatically ?
Press tab to list possible options. Enter empty string to move to the next question.
> PhantomJS
What is the location of your source and test files ?
You can use glob patterns, eg. "js/*.js" or "test/**/*Spec.js".
Enter empty string to move to the next question.
> 
Should any of the files included by the previous patterns be excluded ?
You can use glob patterns, eg. "**/*.swp".
Enter empty string to move to the next question.
> 
Do you want Karma to watch all the files and run the tests on change ?
Press tab to list possible options.
> no
Config file generated at "/home/charley/Desktop/myKarmDemo/karma.conf.js".

初始化完成之后,会在我们的项目中生成一个 karma.conf.js 文件,这个文件就是 Karma 的配置文件。

配置文件比较简单,能够比较轻松的看懂,这里我对原始的配置文件进行简单的修改,结果如下:

// Karma configuration
// Generated on Sun Oct 29 2017 21:45:27 GMT+0800 (CST)
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: false,
 // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['PhantomJS'],// Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: true,
 // Concurrency level
    // how many browser should be started simultaneous
    concurrency: Infinity
  })
}

然后创建一个 src 目录和一个 test 目录,在其中分别创建 index.js 和 index.spec.js 文件。

我要做的测试内容比较简单,对 index.js 中的两个函数(一个加法函数,一个乘法函数)进行测试。

index.js 文件如下:

// 加法函数
function add(x){
    return function(y){
        return x + y;
    }
}
// 乘法函数
function multi(x){
    return function(y){
        return x * y + 1;
    }
}

index.spec.js 文件如下:

describe("运算功能单元测试",function(){
    it("加法函数测试",function(){
        var add5 = add(5)
        expect(add5(5)).toBe(10)
    });
it("乘法函数测试",function(){
        var multi5 = multi(5)
        expect(multi5(5)).toBe(25)
    })
})

单测的代码写好后,就可以使用 karma start 来运行单元测试。由于我们的乘法代码中有错误,因此测试结果是这样的:

myKarmDemo karma start
29 10 2017 22:21:56.283:INFO [karma]: Karma v1.7.1 server started at http://0.0.0.0:9876/
29 10 2017 22:21:56.287:INFO [launcher]: Launching browser PhantomJS with unlimited concurrency
29 10 2017 22:21:56.294:INFO [launcher]: Starting browser PhantomJS
29 10 2017 22:21:56.549:INFO [PhantomJS 2.1.1 (Linux 0.0.0)]: Connected on socket 0h6boaepSUMwG7l2AAAA with id 44948955
PhantomJS 2.1.1 (Linux 0.0.0) 运算功能单元测试 乘法函数测试 FAILED
        Expected 26 to be 25.
        test/index.spec.js:9:31
PhantomJS 2.1.1 (Linux 0.0.0): Executed 2 of 2 (1 FAILED) (0.048 secs / 0.002 secs)

将乘法函数的代码改为正常,再次启用 karma start 进行测试:

29 10 2017 22:23:08.670:INFO [karma]: Karma v1.7.1 server started at http://0.0.0.0:9876/
29 10 2017 22:23:08.673:INFO [launcher]: Launching browser PhantomJS with unlimited concurrency
29 10 2017 22:23:08.685:INFO [launcher]: Starting browser PhantomJS
29 10 2017 22:23:08.940:INFO [PhantomJS 2.1.1 (Linux 0.0.0)]: Connected on socket pl_pZDcAK4rBTpr0AAAA with id 40770640
PhantomJS 2.1.1 (Linux 0.0.0): Executed 2 of 2 SUCCESS (0.045 secs / 0.001 secs)

对了,如果使用 PhantomJS 作为代码的运行环境,其对于 ES6 的支持性不是太好,我在代码中使用了箭头函数,在运行时就报错了。为了解决这个问题,你可以使用 Chrome 或其他浏览器进行测试,也需要安装相应的 launcher,如果你使用 Chrome 浏览器测试,需要安装 karma-chrome-launcher 插件。

或者,你可以使用 Babel 等工具对代码进行转码后进行测试。

使用 PhantomJS 的好处在于其是一个无界面的浏览器运行环境,可以跑在命令行环境中,在某些没有 Chrome 等浏览器服务器环境下比较好用,方便代码验收和集成。

对于 Karma 的介绍就到这里了,本文只是对 Karma 的安装和使用进行了简单的介绍,权当抛砖引玉,至于更多的用法,您可以再进行研究。


目录
相关文章
|
2月前
|
资源调度 测试技术 Linux
一款接口自动化神器—开源接口测试平台Lim(Less is More)
一款接口自动化神器—开源接口测试平台Lim(Less is More)
130 2
|
2月前
|
安全 测试技术 持续交付
接口自动化测试的基本流程
接口自动化测试的基本流程
|
4月前
|
前端开发 JavaScript API
前端 npm anywhere 与 npm now 网页随时真机测试
前端 npm anywhere 与 npm now 网页随时真机测试
38 0
|
4月前
|
机器学习/深度学习 人工智能 算法
软件测试/人工智能|人工智能与自动化测试结合实战-探索人工智能在测试领域中的应用
软件测试/人工智能|人工智能与自动化测试结合实战-探索人工智能在测试领域中的应用
145 0
|
3月前
|
敏捷开发 存储 测试技术
敏捷测试中的挑战和自动化风险
敏捷测试中的挑战和自动化风险
|
2天前
|
测试技术 API 网络架构
Python的api自动化测试 编写测试用例
【4月更文挑战第18天】使用Python进行API自动化测试,可以结合`requests`库发送HTTP请求和`unittest`(或`pytest`)编写测试用例。以下示例: 1. 安装必要库:`pip install requests unittest` 2. 创建`test_api.py`,导入库,定义基础URL。 3. 创建继承自`unittest.TestCase`的测试类,包含`setUp`和`tearDown`方法。 4. 编写测试用例,如`test_get_users`,检查响应状态码和内容。 5. 运行测试:`python -m unittest test_api.py`
12 2
|
1月前
|
数据采集 数据处理 开发工具
argparse是你的好帮手:快速编写自动化脚本、测试脚本、数据处理脚本
argparse是你的好帮手:快速编写自动化脚本、测试脚本、数据处理脚本
|
3月前
|
Web App开发 前端开发 JavaScript
Web前端性能测试方法
Web前端性能测试方法
|
3月前
|
Web App开发 前端开发 测试技术
性能测试分层模型以及前端性能测试工具介绍
性能测试分层模型以及前端性能测试工具介绍
|
3月前
|
JSON 自然语言处理 机器人
接口自动化测试教程:如何使用 Robot Framework
Robot Framework 是一个用于实现自动化测试和机器人流程自动化(RPA)的开放源代码框架。它由一个名为 Robot Framework Foundation 的组织得到推广,得到了多家领军企业在软件开发中的广泛应用。框架以其开放性和灵活性为特点,能够无缝整合各种其他工具,无论团队规模大小,均无需承担额外许可成本。

热门文章

最新文章