前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >常用的前端自动化测试工具介绍 —— Karma

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

作者头像
江咏之
发布2022-06-17 14:09:03
1.5K0
发布2022-06-17 14:09:03
举报
文章被收录于专栏:技术社区技术社区

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

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

对于普通开发者而言,单元测试和功能测试是最常见的两种测试方式,本系列文章要介绍的几个工具是针对这两个方面的。 单元测试是对某一块独立的业务模块进行测试,可以是一个小功能,甚至一个函数。在前端开发中,我们可以选用 Karma 进行代码的单元测试,这个工具十分强大,它集成了像 Jasmine(基于 BDD 的测试框架),PhantomJS(无界面的浏览器) 这些测试套件。还有一些其他有用的功能,比如生成代码覆盖率的报告等。 本文只介绍 Karma 的基本使用。

单元测试工具 Karma

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

代码语言:javascript
复制
npm install karma-cli -g
npm install karma jasmine-core karma-jasmine karma-phantomjs-launcher -D

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

代码语言:javascript
复制
karma init

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

代码语言:javascript
复制
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 的配置文件。 配置文件比较简单,能够比较轻松的看懂,这里我对原始的配置文件进行简单的修改,结果如下:

代码语言:javascript
复制
// 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 文件如下:

代码语言:javascript
复制
// 加法函数
function add(x){
    return function(y){
        return x + y;
    }
}
// 乘法函数
function multi(x){
    return function(y){
        return x * y + 1;
    }
}

index.spec.js 文件如下:

代码语言:javascript
复制
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 来运行单元测试。由于我们的乘法代码中有错误,因此测试结果是这样的:

代码语言:javascript
复制
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 进行测试:

代码语言:javascript
复制
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 的安装和使用进行了简单的介绍,权当抛砖引玉,至于更多的用法,您可以再进行研究。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021-12-24,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 单元测试工具 Karma
相关产品与服务
手游安全测试
手游安全测试(Security Radar,SR)为企业提供私密的安全测试服务,通过主动挖掘游戏业务安全漏洞(如钻石盗刷、服务器宕机、无敌秒杀等40多种漏洞),提前暴露游戏潜在安全风险,提供解决方案及时修复,最大程度降低事后外挂危害与外挂打击成本。该服务为腾讯游戏开放的手游安全漏洞挖掘技术,杜绝游戏外挂损失。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档