JavaScript之调试工具之断言assert

时间:2022-06-16 15:16:43

1.单点断言

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>断言----assert</title>
<style type="text/css">
#results li.pass { color:green; }
#results li.fail { color:red; }
</style>
</head>
<body>
<ul id="results"></ul>
<script type="text/javascript">
function assert(value,desc){
var li = document.createElement("li");
li.className = value ? "pass" : "fail";
li.appendChild(document.createTextNode(desc));
document.getElementById("results").appendChild(li);
}
window.onload = function(){
assert(true,"The test suite is running");
assert(false,"Failed!");
assert(true,"OK");
}
</script>
</body>
</html>

运行:

JavaScript之调试工具之断言assert

2.分组测试断言

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>assert2</title>
<style type="text/css">
#results li.pass { color:green; }
#results li.fail { color:red; }
</style>
</head>
<body>
<div style="color:red;font-weight: bolder; text-align: center;">
测试分组
</div>
<ul id="results"></ul>
<script type="text/javascript">
(function(){
var results;
this.assert = function(value,desc){
var li = document.createElement("li");
li.className = value ? "pass":"failed";
li.appendChild(document.createTextNode(desc));
results.appendChild(li);
if(!value){
li.parentNode.parentNode.className = "fail"
}
return li;//返回li对象
};
this.test = function(name,fn){
results = document.getElementById("results");
results = assert(true,name).appendChild(document.createElement("ul"));
fn();
}
})();
</script>
<script type="text/javascript">
window.onload = function(){
test("A group test.",function(){
assert(true,"A.1 assertion completed.");
assert(true,"A.2 assertion completed.");
assert(true,"A.3 assertion completed.");
}); test("B group test",function(){
assert(true,"B.a assertion completed.");
assert(false,"B.b assertion completed.");
assert(true, "B.c assertion completed.");
});
}
</script>
</body>
</html>

运行:

JavaScript之调试工具之断言assert

3.引用文献:JavaScript忍者秘籍