介绍Node assert, should.js, mocha, Karma, Travis CI

是什么?

  • [Node assert] (http://nodejs.cn/api/assert.html)

    官方说明:assert 模块提供了断言测试的函数,用于测试不变式。
    有严格模式(strict mode)与遗留模式(legacy mode)两种模式,建议只使用严格模式。
    查看 MDN的等式比较指南,了解更多关于等式比较的信息。

  • should.js

    官方说明:should is an expressive, readable, framework-agnostic assertion library. The main goals of this library are to be expressive and to be helpful. It keeps your test code clean, and your error messages helpful.

    有道翻译如下:
    should是一个富有表现力,可读,框架无关的断言库。这个库的主要目标是表达和帮助。它可以保持你的测试代码整洁,并且错误消息也很有用。

  • mocha

    mocha中文学习文档

    Mocha是一个在Node上运行的特性丰富的JavaScript测试框架。让异步测试变得简单和有趣。Mocha测试是连续运行的,允许灵活和准确的报告,同时将未捕获的异常映射到正确的测试用例

    mocha是JavaScript的一种单元测试框架,单元测试是用来对一个模块、一个函数或者一个类来进行正确性检验的测试工作。以测试为驱动的开发模式最大的好处就是确保一个程序模块的行为符合我们设计的测试用例。在将来修改的时候,可以极大程度地保证该模块行为仍然是正确的。

    小本本测试框架选型

  • TDD 和 BDD

    扫描二维码关注公众号,回复: 4014076 查看本文章

    TDD:Test-Driven Development(测试驱动开发)
    是敏捷开发中的一项核心实践和技术,在开发功能代码之前,先编写单元测试用例代码,测试代码确定需要编写什么产品代码(。侧重点偏向开发 -> 开发人员)

    BDD:Behavior Driven Development(行为驱动开发)
    是一种敏捷软件开发的技术,它鼓励软件项目中的开发者、QA和非技术人员或商业参与者之间的协作。(侧重点偏向设计 -> 产品、开发者、测试人员)

  • Karma

    The main goal for Karma is to bring a productive testing environment to developers. The environment being one where they don't have to set up loads of configurations, but rather a place where developers can just write the code and get instant feedback from their tests. Because getting quick feedback is what makes you productive and creative.

    有道翻译如下:
    Karma的主要目标是为开发人员提供高效的测试环境。环境是他们不必设置大量配置的环境,而是开发人员只需编写代码并从测试中获得即时反馈的地方。因为获得快速反馈是让您富有成效和创造力的原因。

    小本本karma Coverage

  • Travis CI

    Travis CI 是目前新兴的开源持续集成构建项目,它与jenkins,GO的很明显的特别在于采用yaml格式,简洁清新独树一帜。

    什么是持续集成?
    注:此处引用文章https://baijiahao.baidu.com/s?id=1587248159486720910&wfr=spider&for=pc

    Travis CI 提供的是持续集成服务(Continuous Integration,简称 CI)。它绑定 Github 上面的项目,只要有新的代码,就会自动抓取。然后,提供一个运行环境,执行测试,完成构建,还能部署到服务器。
    持续集成指的是只要代码有变更,就自动运行构建和测试,反馈运行结果。确保符合预期以后,再将新代码"集成"到主干。

    持续集成的好处在于,每次代码的小幅变更,就能看到运行结果,从而不断累积小的变更,而不是在开发周期结束时,一下子合并一大块代码。

使用Karma

这里介绍使用karma和mocha进行单元测试。断言库使用should。

安装步骤

  • 全局安装 mocha和karma-cli
npm install mocha -g
npm install -g karma-cli
  • 初始化npm包
npm init -y  // -y是默认配置
  • 在项目内安装 karma, mocha, should
npm i karma mocha should --save-dev
  • 初始化测试
karma init
1. Which testing framework do you want to use ? (mocha)  // 默认是jasmine, 按键盘的->键切换成mocha.
2. Do you want to use Require.js ? (no)
3. Do you want to capture any browsers automatically ? (Chrome)
4. What is the location of your source and test files ? (https://cdn.bootcss.com/jquery/2.2.4/jquery.js, node_modules/should/should.js, test/**.js)
5. Should any of the files included by the previous patterns be excluded ? ()
6. Do you want Karma to watch all the files and run the tests on change ? (yes)
  • 启动测试
karma start

也可以在package.json中配置scripts:
运行npm run test

"scripts": {
"test": "karma start"
},

测试

karma 的配置文件中,加入我们的测试文件

// list of files / patterns to load in the browser
files: [
  'https://cdn.bootcss.com/jquery/2.2.4/jquery.js',
  'node_modules/should/should.js',
  'test/**.js'
],

在test/test.js中写入我们的测试用例:

describe('jQuery', function () {
  it('should have jQuery', function () {
    if (!window.jQuery) {
      throw new Error('查看下 karma.conf.js 配置项 files 是否正确')
    }
  })

  it('should able to get a body', function () {
    var $body = $('body')
    $body.length.should.equal(1)
    $body[0].should.equal(document.getElementsByTagName('body')[0])
  })

  describe('should able to trigger an event', function () {
    var ele
    before(function () {
      ele = document.createElement('button')
      document.body.appendChild(ele)
    })

    it('should able trigger an event', function (done) {
      $(ele).on('click', function () {
        done()
      }).trigger('click')
    })

    after(function () {
      document.body.removeChild(ele)
      ele = null
    })
  })

  it('should able to request https://raw.githubusercontent.com/FE-star/exercise1/master/test/test.js', function (done) {
    // 使用 jQuery.ajax 请求 https://raw.githubusercontent.com/FE-star/exercise1/master/test/test.js,并验证是否拿到文件
    
    var url = "https://raw.githubusercontent.com/FE-star/exercise1/master/test/test.js"
    $.ajax({
      type: "GET",
      url: url,
      success: function(msg){
        done()
      }
    });
  })
})

测试成功:

这里贴一下 karma.conf.js 的基本配置:

// Karma configuration
// Generated on Sat Nov 10 2018 18:53:08 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: ['mocha'],


    // list of files / patterns to load in the browser
    files: [
      'https://cdn.bootcss.com/jquery/2.2.4/jquery.js',
      'node_modules/should/should.js',
      'test/**.js'
    ],


    // list of files / patterns 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,

    // Concurrency level
    // how many browser should be started simultaneous
    concurrency: Infinity
  })
}

接入Travis CI

说明: 这里演示把托管在Github上的项目使用Travis Ci来做集成测试。

准备工作:

  • 打开https://travis-ci.org/ travis-cli官网。
  • 把Github的项目同步到Travis Ci的管理后台:

  • 针对某个项目打开开关,如exercise3打开了开关:

接下来在文件的根目录下创建一个文件夹.travis.yml
简单配置:

# 使用的语言
language: node_js
# 使用的nodejs版本
node_js:
  - "8"
addons:
  chrome: stable
before_script:
  - "export DISPLAY=:99.0"
  - "sh -e /etc/init.d/xvfb start"
# 上面句话是为了在Linux系统下默认没有Chrome, 无法启动而测试不通过。

install:
  - npm install -g karma-cli

把修改好的代码推送到github仓库上,开开travis官网,你就发现你的项目开始构建了。

猜你喜欢

转载自www.cnblogs.com/arissy/p/9940341.html