Williammer
5/29/2014 - 10:03 AM

javascript.groupAsynTest.html - the great code to implement group asyn test in 《javascript ninja》

javascript.groupAsynTest.html - the great code to implement group asyn test in 《javascript ninja》

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
	<meta property="wb:webmaster" content="edcf77ed05a8765f" />
	<title>ninja test group asyn</title>
	<meta name="viewport" content="width=device-width"> 

<style>
	#result li.passed { color: blue; }
	#result li.failed { color: red; }
	</style>
</head>
	
<body>	
	<ul id="result"></ul>
</body>
</html>
	<script>
	/*  Appreciation on codes
		assert(), test() is defined in an immediate-invoked function(provides a scope sandbox, good use of this, pointing to window)
		for asyn:
		Lock process with pause/resume
	*/
	(function(){
		var queue = [], pause = false, count = 0,  results;
		this.assert = function(value, msg){
			var li = document.createElement('li');
			li.className = value? 'passed': 'failed';
			li.appendChild(document.createTextNode(msg));
			results.appendChild(li);
			if(!value){
				li.parentNode.parentNode.className = 'failed';
			}
			return li;
		};
		
		this.pause = function(){
			pause = true;
		};
		
		this.resume = function(){
			pause = false;
			setTimeout( run, 1000);
		};
		// test group
		this.test = function(name, fn){
		
			queue.push(function(){
				results = document.getElementById('result');
				results = assert(true, name).appendChild(document.createElement('ul'));// results turn sub
				fn();
			});
			
			run(); //first run
			
		};
		function run() {
			//console.log('run count:'+(++count));
			//console.log('run elapsed time:'+(new Date().getTime() - now));
			if(!pause && queue.length) {
				//console.log('paused.');
				queue.shift()();
				if(!pause) { //judge after shift and execute the fn.
					//console.log('insdie paused.');
					resume();
				}
			}
		}
	})();
	
	// onload
	window.onload = function(){
		// now = new Date().getTime();
		test('asyn test1', function(){ 
			//console.log('before pause.');
			pause();
			setTimeout(function(){
				//console.log('before assert.'+(new Date().getTime() - now));
				assert(true, 'test case1 completed.');
				assert(false, 'test case1 completed.');
				resume();
			}, 1000);
			
		});
		test('asyn test2', function(){
			pause();
			setTimeout(function(){
				assert(true, 'test case2 completed.');
				resume();
			}, 1000);
			
		});
	};
	</script>