QUnit单元测试

首先需要了解Qunit是个什么东西?为什么要用这个东西?我也是最近才发觉用单元测试的好处,Qunit在众多的单元测试中我觉得是很不错的,是jq团队写的一个东西/

基本配置:

<link rel="stylesheet" href="http://code.jquery.com/qunit/qunit-1.11.0.css" />

<script src="http://code.jquery.com/qunit/qunit-1.11.0.js"></script>

一篇很不错的入门介绍:http://www.zhangxinxu.com/wordpress/2013/04/qunit-javascript-unit-test-%E5%8D%95%E5%85%83%E6%B5%8B%E8%AF%95/

里面讲的很详细,基本可以学会....

贴上我写得一段入门测试代码:

function format(string,values){
	for(var key in values){
			string = string.replace(new RegExp("{"+key+"}",'g'),values[key]);
	}	
	return string;
}

test("basics",function(){
	var values = {
		name:"World"	
	};
	equal(format("hello,{name}",values),"hello,World","单个匹配成功");
	equal(format("Hello,{name}, how is {name} today?", values),"Hello,World, how is World today?", "多个匹配成功" );	
});

var Money = function(options){
	this.amount = options.amount || 0;
	this.template = options.template || 0;
	this.symbol = options.symbol || '$';
};
Money.prototype = {
	add:function(toAdd){
		this.amount+=toAdd;
	},	
	toString:function(){
		return this.template
				.replace("{symbol}",this.symbol)
				.replace("{amount}",this.amount);
	}	
};
Money.euro = function(amount){
	return new Money({
		amount:amount,
		template:"{amount}{symbol}",
		symbol:"EUR"	
	});
}

module("Money",{  
	setup:function(){
		this.dollar = new Money({
			amount:15.5	
		});
		this.euro = Money.euro(14.5);
	},
	teardown:function(){
		//可以清除this.dollar和this.euro
	}	
});

test("add",function(){
	equal(this.dollar.amount,15.5);
	this.dollar.add(16.1);
	equal(this.dollar.amount,31.6);
});
test("toString",function(){
	equal(this.dollar.toString(),"$15.5");
	equal(this.euro.toString(),"14.5 EUR");
});

//异步调用测试
test("async",function(){
	stop();
	$.getJSON("resource",function(result){
		deepEqual(result,{
			status:"ok"	
		});	
		start();
	});	
});

html端可以这么写:

<!DOCTYPE html>
<html>
<head>
  	<meta charset="utf-8">
  	<title>QUnit Example</title>

  	<link rel="stylesheet" href="http://code.jquery.com/qunit/qunit-1.11.0.css" />
	<script type="text/javascript" >

	</script>
</head>
<body>
  <h1 id="qunit-header">QUnit测试</h1>
  <h2 id="qunit-banner"></h2>
  <div id="qunit-testrunner-toolbar"></div>
  <h2 id="qunit-userAgent"></h2>
  <ol id="qunit-tests"></ol>
  <div id="qunit-fixture">测试标记</div>
  <script src="http://code.jquery.com/qunit/qunit-1.11.0.js"></script>
  <script src="test.js"></script>
</body>
</html>

 

  

posted @ 2013-05-08 12:42  GM_Lv  阅读(272)  评论(0编辑  收藏  举报