Javascript CI篇(1)- Jasmine 基础学习

jasmine 简介

Jasmine 是一个含有丰富的断言库的测试框架。目前我用的最新的版本是:2.6

基础篇

命令行中环境中使用jasmine

  • 安装

npm install -g jasmine //这里采用全局安装,好处是直接cmd就能用,也可以采用本地安装
  • 初始化配置文件

jasmine init
  • 生成的配置文件如下jasmine.json

{
  "spec_dir": "spec", //spec 所在目录
  "spec_files": [
    "**/*[sS]pec.js"        //测试文件,相对于spec_dir
  ],
  "helpers": [
    "helpers/**/*.js"       //测试前辅助文件,相对于spec_dir
  ],
  "stopSpecOnExpectationFailure": false, //
  "random": false
}
  • 运行测试

//直接根据配置文件运行
jasmine 

//执行测试某个文件
jasmine appSpec.js

node 环境中使用jasmine

var Jasmine = require('jasmine');
var jasmine = new Jasmine();
  • 加载配置文件

//方式1
jasmine.loadConfigFile('spec/support/jasmine.json');

//方式2
jasmine.loadConfig({
    spec_dir: 'spec',
    spec_files: [
        'appSpec.js',
        'requests/**/*[sS]pec.js',
        'utils/**/*[sS]pec.js'
    ],
    helpers: [
        'helpers/**/*.js'
    ]
});
  • 自定义测试完成事件

jasmine.onComplete(function(passed) {
    if(passed) {
        console.log('All specs have passed');
    }
    else {
        console.log('At least one spec has failed');
    }
});
  • 自定义测试报告

jasmine.configureDefaultReporter({
    timer: new this.jasmine.Timer(),
    print: function() {
        process.stdout.write(util.format.apply(this, arguments));
    },
    showColors: true,
    jasmineCorePath: this.jasmineCorePath
});
var CustomReporter = require('./myCustomReporter');
var customReporter = new CustomReporter();

jasmine.addReporter(customReporter);
  • 执行测试

jasmine.execute();
jasmine.execute(['fooSpec.js'], 'a spec name');
  • 简单完整的测试案例

var Jasmine = require('jasmine');
var jasmine = new Jasmine();

jasmine.loadConfigFile('spec/support/jasmine.json');
jasmine.configureDefaultReporter({
    showColors: false
});
jasmine.execute();

你可能感兴趣的:(javascript,ci)