Karma (Test runner)
Karma
https://baike.baidu.com/item/%E7%BE%AF%E7%A3%A8/7618552?fromtitle=Karma&fromid=878453
1,意译作“业”。业;行动;命运。一个人生命中的自然与必然事件,由前世的作为所决定。含有善恶、苦乐果报之意味,亦即与因果关系相结合的一种持续作用力。,2,在佛教中,既是“作持”性质的戒条(属于各部“广律”的犍度篇部分),更是僧团中的议事规则。举凡授戒、说戒、忏悔,乃至各种僧团公共事条的处理所应遵行的一定程序,统称为“羯磨”,故此词意译为“办事”。
https://astrisk.github.io/javascript/2017/04/20/js-karma/
Karma 是Google 开源的一个基于Node.js 的 JavaScript 测试执行过程管理工具(Test Runner)。 Karma 可以在不同的桌面或移动设备浏览器上,或在持续集成的服务器上测试 JavaScript 代码。Karma 支持 Chrome、ChromeCanary、 Safari、Firefox、 IE、Opera、 PhantomJS,知道如何捕获浏览器正使用的默认路径,这些路径可能在启动器配置文件被忽视(overridden)。Karma 就是一个可以和多重测试框架协作的测试执行过程管理工具,它有针对Jasmine、 Mocha 和AngularJS 的适配器,它也可以与 Jenkins 或 Travis 整合,用于执行持续集成测试。
安装:
http://blog.fens.me/nodejs-karma-jasmine/
npm install -g karma// configkarma init
// runkarma start
详细见:
http://www.cnblogs.com/wushangjue/p/4539189.html
配置:
karma.config.js
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine'],
files: ['*.js'],
exclude: ['karma.conf.js'],
reporters: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
captureTimeout: 60000,
singleRun: false
});
};
覆盖率报告:
http://blog.fens.me/nodejs-karma-jasmine/
npm install karma-coverage
reporters: ['progress','coverage'],
preprocessors : {'src.js': 'coverage'},
coverageReporter: {
type : 'html',
dir : 'coverage/'
}
Jasmine 断言API
https://jasmine.github.io/2.0/custom_matcher.html
Expectations
Expectations are built with the function
expectwhich takes a value, called the actual. It is chained with a Matcher function, which takes the expected value.describe("The 'toBe' matcher compares with ===", function() {Matchers
Each matcher implements a boolean comparison between the actual value and the expected value. It is responsible for reporting to Jasmine if the expectation is true or false. Jasmine will then pass or fail the spec.
it("and has a positive case", function() {
expect(true).toBe(true);
});Any matcher can evaluate to a negative assertion by chaining the call to
expectwith anotbefore calling the matcher.it("and can have a negative case", function() {
expect(false).not.toBe(true);
});
});Included Matchers
Jasmine has a rich set of matchers included. Each is used here - all expectations and specs pass. There is also the ability to write custom matchers for when a project's domain calls for specific assertions that are not included below.
将ES6转换为 UMD
UMD:
http://web.jobbole.com/82238/
既然CommonJs和AMD风格一样流行,似乎缺少一个统一的规范。所以人们产生了这样的需求,希望有支持两种风格的“通用”模式,于是通用模块规范(UMD)诞生了。
不得不承认,这个模式略难看,但是它兼容了AMD和CommonJS,同时还支持老式的“全局”变量规范:
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD
define(['jquery'], factory);
} else if (typeof exports === 'object') {
// Node, CommonJS之类的
module.exports = factory(require('jquery'));
} else {
// 浏览器全局变量(root 即 window)
root.returnExports = factory(root.jQuery);
}
}(this, function ($) {
// 方法
function myFunc(){};
// 暴露公共方法
return myFunc;
}));
http://www.cnblogs.com/snandy/archive/2012/03/19/2406596.html
AMD以浏览器为第一(browser-first)的原则发展,选择异步加载模块。它的模块支持对象(objects)、函数(functions)、构造器(constructors)、字符串(strings)、JSON等各种类型的模块。因此在浏览器中它非常灵活。
CommonJS module以服务器端为第一(server-first)的原则发展,选择同步加载模块。它的模块是无需包装的(unwrapped modules)且贴近于ES.next/Harmony的模块格式。但它仅支持对象类型(objects)模块。
这迫使一些人又想出另一个更通用格式 UMD(Universal Module Definition)。希望提供一个前后端跨平台的解决方案。
UMD的实现很简单,先判断是否支持Node.js模块格式(exports是否存在),存在则使用Node.js模块格式。
再判断是否支持AMD(define是否存在),存在则使用AMD方式加载模块。前两个都不存在,则将模块公开到全局(window或global)。
https://github.com/umdjs/umd
This repository formalizes the design and implementation of the Universal Module Definition (UMD) API for JavaScript modules. These are modules which are capable of working everywhere, be it in the client, on the server or elsewhere.
The UMD pattern typically attempts to offer compatibility with the most popular script loaders of the day (e.g RequireJS amongst others). In many cases it uses AMD as a base, with special-casing added to handle CommonJS compatibility.
将ES6模块转换为UMD代码
https://babel.bootcss.com/docs/plugins/transform-es2015-modules-umd/
输入
export default 42;
输出
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["exports"], factory);
} else if (typeof exports !== "undefined") {
factory(exports);
} else {
var mod = {
exports: {}
};
factory(mod.exports);
global.actual = mod.exports;
}
})(this, function (exports) {
"use strict"; Object.defineProperty(exports, "__esModule", {
value: true
}); exports.default = 42;
});
安装
npm install --save-dev babel-plugin-transform-es2015-modules-umd
用法
通过 .babelrc(推荐)
.babelrc
{
"plugins": ["transform-es2015-modules-umd"]
}当模块在浏览器中运行时,你可以覆盖特定的库的名称。例如
es-promise库将自己暴露为global.Promise而不是global.es6Promise。这可以通过如下代码实现:{
"plugins": [
["transform-es2015-modules-umd", {
"globals": {
"es6-promise": "Promise"
}
}]
]
}
自己动手
https://github.com/fanqingsong/code-snippet/tree/master/javascript/karma_demo
karma.config.js
// Karma configuration
// Generated on Thu Aug 16 2018 01:07:59 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', 'browserify'], /**
* 需要加载到浏览器的文件列表
*/
// list of files / patterns to load in the browser
files: [
'test/*[s|S]pec.js',
], // list of files / patterns to exclude
exclude: [
'karma.conf.js'
], // preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'test/*[s|S]pec.js' : [ 'browserify' ]
}, //karma-browserify 配置,配置为使用 babelify
browserify: {
debug: true,
transform: [['babelify', {presets: ['es2015'], plugins: ['transform-class-properties']}]]
}, // test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress','kjhtml'], // 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,
})
}
Player.js
class Player {
constructor() {
}
play(song) {
this.currentlyPlayingSong = song;
this.isPlaying = true;
}
pause() {
this.isPlaying = false;
}
resume() {
if (this.isPlaying) {
throw new Error("song is already playing");
}
this.isPlaying = true;
}
makeFavorite() {
this.currentlyPlayingSong.persistFavoriteStatus(true);
}
};
export default Player;
Song.js
class Song {
constructor() {
}
persistFavoriteStatus(value) {
// something complicated
throw new Error("not yet implemented");
}
}
export default Song;
testPlayerSpec.js
import Player from "../js/Player";
import Song from '../js/Song'; console.log("====================================") describe("Player", function() {
var player;
var song; beforeEach(function() {
player = new Player();
song = new Song(); jasmine.addMatchers({
toBePlaying: function () {
return {
compare: function (actual, expected) {
var player = actual; return {
pass: player.currentlyPlayingSong === expected && player.isPlaying
}
}
};
}
});
}); console.log("====================================!!! out")
it("should be able to play a Song", function() {
console.log("====================================!!!")
player.play(song);
expect(player.currentlyPlayingSong).toEqual(song); //demonstrates use of custom matcher
expect(player).toBePlaying(song);
}); describe("when song has been paused", function() {
beforeEach(function() {
player.play(song);
player.pause();
}); it("should indicate that the song is currently paused", function() {
expect(player.isPlaying).toBeFalsy(); // demonstrates use of 'not' with a custom matcher
expect(player).not.toBePlaying(song);
}); it("should be possible to resume", function() {
player.resume();
expect(player.isPlaying).toBeTruthy();
expect(player.currentlyPlayingSong).toEqual(song);
});
}); // demonstrates use of spies to intercept and test method calls
it("tells the current song if the user has made it a favorite", function() {
spyOn(song, 'persistFavoriteStatus'); player.play(song);
player.makeFavorite(); expect(song.persistFavoriteStatus).toHaveBeenCalledWith(true);
}); // //demonstrates use of expected exceptions
// describe("#resume", function() {
// it("should throw an exception if song is already playing", function() {
// player.play(song); // expect(function() {
// player.resume();
// }).toThrowError("song is already playing");
// });
// });
});

参考:
http://blog.leanote.com/post/y.ruibin09@gmail.com/%E5%89%8D%E7%AB%AF-es6
https://wenjs.me/p/es6-testing-workflow-with-karma
Karma (Test runner)的更多相关文章
- karma作为jQuery单元测试Runner
karma作为angular测试runner出现,如果你使用过karma一定感受到这很不错的javascript测试runner.简单干净的配置文件karma.config.js,以及karma in ...
- karma的基础应用之与fis结合
一.介绍 1. karma是单元测试运行框架,可以集成jasmine断言库,也支持babel. 2.fis是百度前端团队开源推出的前端工程化管理工具. 二.karma的基础应用 1.karma的基础a ...
- Karma:1. 集成 Karma 和 Jasmine 进行单元测试
关于 Karma 会是一个系列,讨论在各种环境下,使用 Karma 进行单元测试. 本文讨论 karma 集成 Jasmine 进行单元测试. 初始化 NPM 实现初始化 NPM 包管理,创建 pac ...
- Vue的自动化测试
前言 为什么我们需要测试? 让产品可以快速迭代,同时还能保持高质量 -- 阮一峰 持续集成是什么? 对于一些相对稳定的系统级别页面,自动化测试在提高测试的效率的方面起到非常重要的作用.前端的自动化测试 ...
- WebStorm 7.0 支持更多的Web技术
JetBrains刚刚发布了WebStorm 7.0 GA,支持EJS.Mustache.Handlebars.Web组件.Stylus.Karma.Istanbul.Compass,并增强了很多功能 ...
- Rails 5 Test Prescriptions 第10章 Unit_Testing JavaScript(新工具,learn曲线太陡峭,pass)
对Js的单元测试是一个大的题目.作者认为Ruby的相关测试工具比Js的测试工具更灵活 大多数Js代码最终是关于响应用户的行为和改变DOM中的元素 没有什么javascript的知识点.前两节用了几个新 ...
- 利用Angularjs测试引擎Karma进行自动化单元测试
Karma是Google用于angularjs框架单元测试的js引擎(javascript test runner ), angular1 和angular2项目源码的单元测试都是基于karma和ja ...
- Karma+Jasmine实现自动化单元测试
1.Karma介绍 Karma是Testacular的新名字,在2012年google开源了Testacular,2013年Testacular改名为Karma.Karma是一个让人感到非常神秘的名字 ...
- Karma +Jasmine+ require JS进行单元测试并生成测试报告、代码覆盖率报告
1. 关于Karma Karma是一个基于Node.js的JavaScript测试执行过程管理工具(Test Runner). 该工具可用于测试所有主流Web浏览器,也可集成到CI(Continuou ...
随机推荐
- LVS+Keepalived实现mysql的负载均衡
1 初识LVS:Linux Virtual Server 1.1 LVS是什么 LVS是Linux Virtual Server的简称,也就是Linux虚拟服务器, 是一个由章文嵩博士发起 ...
- C#基础知识之关键字
关键字是 C# 编译器预定义的保留字.这些关键字不能用作标识符,但是,如果您想使用这些关键字作为标识符,可以在关键字前面加上 @ 字符作为前缀.在 C# 中,有些关键字在代码的上下文中有特殊的意义,如 ...
- 大数据平台Lambda架构详解
Lambda架构由Storm的作者Nathan Marz提出.旨在设计出一个能满足.实时大数据系统关键特性的架构,具有高容错.低延时和可扩展等特. Lambda架构整合离线计算和实时计算,融合不可变( ...
- w3m 使用总结
安装 sudo apt install w3m终端 w3m www.baidu.com 即可打开w3m是个开放源代码的命令行下面的网页浏览器.一般的linux系统都会自带这个工具,可以通过它在命令行下 ...
- 转://ORA-00603,ORA-27501,ORA-27300,ORA-27301,ORA-27302故障案例一则
背景介绍: 这是一套windows的rac系统.数据库后台日志报ORA-00474:SMON process terminated with error.接着报ORA-00603,ORA-27501, ...
- wxWidgets 和 QT 之间的选择
(非原创,网络摘抄) 跨平台的C++ GUI工具库很多,可是应用广泛的也就那么几个,Qt.wxWidgets便是其中的翘楚这里把GTK+排除在外,以C实现面向对象,上手相当困难,而且Windows平台 ...
- PHP利用多进程处理任务
PHP多进程一般应用在PHP_CLI命令行中执行php脚本,不要在web访问时使用. 多进程处理分解任务一般要比单进程更快. php查看是否安装多进程模块: php -m | grep pcn ...
- SpringBoot整合RabbitMQ-服务安装
本系列是学习SpringBoot整合RabbitMQ的练手,包含服务安装,RabbitMQ整合SpringBoot2.x,消息可靠性投递实现等三篇博客. 学习路径:https://www.imooc. ...
- PTA 天梯赛练习 7-11 玩转二叉树-二叉树重建
以前就思考过这个问题,但是没有深入的想过,这是一种叫二叉树重建的典型题目 如果给出中序和前序,求出后序遍历. 这道题则求的是交换儿子节点的层序遍历. 二叉树的重建应该怎么重建,首先我们知道,先根遍历, ...
- git修改已push的commit信息
本条适用于修改已push的最新的commit信息,确保本地的文件是最新的. 使用 git commit --amend 命令,(修改最近一次提交的注释信息),会进入到vim 编辑器 编辑提交信息,保存 ...