关于JavaScript测试工具:QUnit, Jasmine, MoCha
在进行前端开发过程中,在某些场景下,需要通过编写单元测试来提高代码质量。而JavaScript常用的单元测试框架有这几个:QUnit, Jasmine, MoCha.下面就基于这三个工具,简单做一比较:
1. QUnit
QUnit是一个JavaScript单元测试框架. 它是个强大,容易使用和上手的JavaScript单元测试框架.它被用于进行 jQuery, jQuery UI and jQuery 移动工程的测试,以及其他通用的JavaScript代码测试.
Features:
- Similar to server-side frameworks(JUnit, Nunit)
- Built by the jQuery team
- Used to test jQuery's features
- No dependencies
- Can test server-side JavaScript
使用方法:
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>QUnit Example</title>
<link rel="stylesheet" href="/resources/qunit.css">
</head>
<body>
<div id="qunit"></div>
<div id="qunit-fixture"></div>
<script src="/resources/qunit.js"></script>
<script src="/resources/tests.js"></script>
</body>
</html> tests.js:
test( "hello test", function() {
ok( 1 == "1", "Passed!" );
});
断言方法:
- ok(state, message)
- equal(actual, expected, message)
- notEqual (actual, expected, message)
- deepEqual (actual, expected, message)
- notDeepEqual(actual, expected, message)
- strictEqual (actual, expected, message)
- notStrictEqual(actual, expected, message)
- raises (actual, expected, message)
2. Jasmine
asmine is a behavior-driven development framework for testing JavaScript code. It does not depend on any other JavaScript frameworks. It does not require a DOM. And it has a clean, obvious syntax so that you can easily write tests.
Since describe and it blocks are functions, they can contain any executable code necessary to implement the test. JavaScript scoping rules apply, so variables declared in a describe are available to any it block inside the suite.
Features:
- Open Source Framework
- Behavior Driven Development framework
- Supports both client-side and server-side testing
行为驱动开发:Behavior Driven Development:
Write a failing acceptance test <--> Write a failing unit test <--> Write code to pass the test
基本用法:
Using the default model SpecRunner.html which referenced jasmine.css, jasmine.js, and jasmine-html.js. Write your own spec as below:
MySpec.js
describe("MyClass", function() { it("should be true", function() {
expect(true).toBeTruthy();
}); it("should be false", function() {
expect(true).toBeFalsy();
});
});
Built-in Matchers (not):
- expect(x).(not.)toEqual(y);
- expect(x).(not.)toBe(y);
- expect(x ).(not.)toMatch(pattern);
- expect(x ).(not.)toBeDefined();
- Expect(x).(not.)toBeUndefined();
- expect(x ).(not.)toBeNull();
- expect(x ).(not.)toBeTruthy();
- expect(x ).(not.)toBeFalsy();
- expect(x ).(not.)toContain(y);
- expect(x ).(not.)toBeLessThan(y);
- expect(x ).(not.)toBeGreaterThan(y);
- expect(function(){ fn ();}).(not.)toThrow(ex);
Creating Custom Matcher:
steps:
1. Typically created in a beforeEach
2. this.addMatchers ()
Example:
beforeEach(function() {
this.addMatchers ({
toBeFive: function() {
return this.actual === 5;
}
});
});
Skipping tests:
Add an “x” in front of the describe or the it function
3. Mocha
Mocha is a feature-rich JavaScript test framework running on node and the browser, making asynchronous testing simple and fun. Mocha tests run serially, allowing for flexible and accurate reporting, while mapping uncaught exceptions to the correct test cases.
Features:
- Open Source Framework
- Started in Node
- Supports both client-side and server-side testing
- Supports both BDD and TDD style tests
- Supports both command line and browser
- Supports any JavaScript assertion library (YUI Port, expect.js, should.js, jshould.js, assert.js, chai.js)
- Supports asynchronous testing
- Requires an assertion library
Usage:
html
<!DOCTYPE html>
<html>
<head>
<title>Mocha</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="mocha.css" />
</head>
<body>
<div id="mocha"></div>
<script src="mocha.js"></script>
<script src="chai.js"></script>
<script>mocha.setup('tdd')</script>
<script>expect = chai.expect;</script>
<script src="test.js"></script>
<script>
mocha.run();
</script>
</body>
</html>
(QUnit style)test.js
suite('my first suite'); beforeEach(function() {
console.log('setup');
}); afterEach(function() {
console.log('teardown');
}); before(function() {
console.log('before');
}); after(function() {
console.log('after');
}); test('test 1', function() {
expect(1).to.equal(1);
console.log('test');
});
(TDD style)test.js
suite('my first suite', function() { setup(function() {
console.log('setup');
}); teardown(function() {
console.log('teardown');
}); before(function() {
console.log('before');
}); after(function() {
console.log('after');
}); test('test 1', function() {
expect(1).to.equal(1);
console.log('test');
}); });
(BDD style)test.js
describe('my first suite', function() { beforeEach(function() {
console.log('setup');
}); afterEach(function() {
console.log('teardown');
}); before(function() {
console.log('before');
}); after(function() {
console.log('after');
}); it('should be my first test', function() {
expect(1).to.equal(1);
console.log('test');
}); describe('inner suite', function() { it('should be my second test', function() {
expect(2).to.equal(2);
console.log('test 2');
}); }); });
Three different assertion syntaxes in Chai js
Assert: var assert = chai.assert;
Expect: var expect = chai.expect;
Should: var should = chai.should(); // notice should is a function
Writing & Running Mocha Tests
TDD and BDD style tests:
(see above usage part)
Filtering:
In the test url, add ?grep=keyword can filter tests.
View source code:
Click on the test, the source code should display.
Exclusive Tests:
Only display one test: it.only('...', function(){...})
Only display one block tests: describe.only('...', function(){...})
Skipping Tests:
Skip one test: it.skip('...', function(){...})
Skip one block test: describe.skip('...', function(){...})
Pending Test:
Only have the description no function: it('...');
Global Leaks:
Newer version does not have this problem.
Slow Test:
Debug source code in developer tool, set break point to one test, you will see the time of the test spent.
Asynchronous Tests with Mocha
it('should be something', function(done){
...
done();
})
Timeout:
The default timeout is 2 seconds for each test.
mocha.setup({timeout:3000}); // set timeout for all tests describe('Outer Describe', function() {
it('should be asynchronous', function(done) {
this.timeout(2500); // setup timeout only for this test
setTimeout(function() {
expect(1).to.equal(1);
done();
}, 2400);
})
});
Comparison
QUnit is very easy to get started with, as you only need to include two files(qunit.css and qunit.js) and a little bit of markup, then you can start writing tests. QUnit is TDD style tests.
QUnit 是非常容易上手,你仅仅需要包含两个文件(qunit.css and qunit.js)和一些很少的标记,然后就可以开始编写测试了。QUnit是一种TDD风格的测试;
Jasmine is easier to get started – it’s all-in-one package will generally get you and a team up and testing much faster, and you’ll be in good hands with it. Jasmine is BDD style tests.
jasmine 是很容易开始---它是 all-in-one package ,可以让你和一个组测试起来很快速,并且你可以很快的上手,Jasmine是一种BDD风格的测试;
Mocha is significantly more flexible, but you have to piece it together yourself. There is no spy framework built in to Mocha, so most people use sinon.js. There’s no assertion framework built in to Mocha either, so you’ll have to pick one. Chai is the popular one, but there are many, many others available. You can also configure Mocha for BDD (jasmine style) or TDD (QUnit style) easily. But you have to pick and choose how you want Mocha to work. This flexibility is great because you can build the test environment that you really want. But it means you have more work to do, more individual pieces to maintain / keep up to date, etc.
关于JavaScript测试工具:QUnit, Jasmine, MoCha的更多相关文章
- 前端技术之:JavaScript测试工具
Mocha 一个用于Node.js与浏览器端的简单.自由.有趣的JavaScript测试框架. https://mochajs.org/ https://github.com/mochajs/moch ...
- JavaScript测试工具
大家都知道Javascript的测试比较麻烦,一般是开发使用一些浏览器的插件比如IE develop bar或是firebug来调试,而测试往往需要通过页面展示后的js错误提示来定位.那么还有其他比较 ...
- JavaScript测试工具比较: QUnit, Jasmine, and Mocha
1. QUnit A JavaScript Unit Testing framework. QUnit is a powerful, easy-to-use JavaScript unit testi ...
- 测试工具使用-Qunit单元测试使用过程
031302620 应课程要求写一篇单元测试工具的博客,但是暂时没用到java,所以不想使用junit(对各种类都不熟悉的也不好谈什么测试),原计划是要用phpunit,但是安装经历了三个小时,查阅各 ...
- WEB前端常用的测试工具
一.QUnit 前端测试工具 QUnit是一个强大的JavaScript单元测试框架,该框架是由jQuery团队的成员所开发,并且是jQuery的官方测试套件.Qunit是Jquery的单元测试框架, ...
- javascript测试框架mocha
node测试框架mocha 简单.灵活.有趣,mocha是一个功能丰富的javascript测试框架,运行在node和浏览器中,使异步测试变得更加简单有趣.http://mochajs.org/ 安装 ...
- JavaScript开发工具大全
译者按: 最全的JavaScript开发工具列表,总有一款适合你! 原文: THE ULTIMATE LIST OF JAVASCRIPT TOOLS 译者: Fundebug 为了保证可读性,本文采 ...
- angularJS测试一 Karma Jasmine Mock
AngularJS测试 一 测试工具 1.NodeJS领域:Jasmine做单元测试,Karma自动化完成单元测试,Grunt启动Karma统一项目管理,Yeoman最后封装成一个项目原型模板,npm ...
- modern.IE – Web 开发必备的 IE 浏览器测试工具
modern.IE 是微软推出的一个开发人员中心,提供免费的工具和资源,旨在使您能够花更少的时间来测试各种版本的 Internet Explorer,并留出更多时间在现代 Web 上构建重要的内容.m ...
随机推荐
- Linux下串口编程【转】
本文转载自:http://blog.csdn.net/w282529350/article/details/7378388 /************声明:本人只是见到这篇文章对我帮助很大才转载的,但 ...
- __ATTRIBUTE__ 你知多少?【转】
转自:http://www.cnblogs.com/astwish/p/3460618.html GNU C 的一大特色就是__attribute__ 机制.__attribute__ 可以设置函数属 ...
- flex datagrid 换行
<mx:DataGrid id="myGrid" width="100%" height="90%" headerStyleName= ...
- java中的反射机制,以及如何通过反射获取一个类的构造方法 ,成员变量,方法,详细。。
首先先说一下类的加载,流程.只有明确了类这个对象的存在才可以更好的理解反射的原因,以及反射的机制. 一. 类的加载 当程序要使用某个类时,如果该类还未被加载到内存中,则系统会通过加载,连接,初始化三 ...
- C#:向控件添加信息类
using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; names ...
- JavaScript脚本语言基础(一)
导读: JavaScript代码嵌入HTML文档 JavaScript代码运行方式 第一个实例 JavaScript的三种对话框 定义JavaScript变量 JavaScript运算符和操作符 Ja ...
- Android调试常用的工具简单介绍
配置Android环境的时候,我们需要安装sdk.在sdk的目录下: platform-tools 目录下的adb tool下的: ddms.bat adb :可以cd 当前目录,然后使用相应的命令, ...
- 【转】Cookie和Session的区别详解
转载地址:http://www.phperzone.cn/portal.php?aid=541&mod=view 一.cookie机制和session机制的区别 具体来说cookie机制采用的 ...
- D类 E类地址
D类地址不分网络地址和主机地址,它的第1个字节的前四位固定为1110.⑵ D类地址范围:224.0.0.0到239.255.255.255D类地址用于多点播送.D类IP地址第一个字节以“lll0”开始 ...
- c# monitor锁
当多个线程在并发的时候,难免会碰到相互冲突的事情,比如最经典的ATM机的问题,并发不可怕,可怕的是我们没有能力控制. 线程以我的理解可以分为三种 ① 锁. ② 互斥. ③ 信号. 好,这一篇主要整理“ ...