用JsUnit测试和跟踪Javascript

最近读Ajax基础教程,读到了用JsUnit测试和跟踪Javascript,感觉不错。

一,用JsUnit测试Javascript,

1,准备好JsUnit,可以从http://sourceforge.net/projects/jsunit/ 这儿下载JsUnit包,解压到工程文件下,JsUnit断言方法

assert([comment], booleanValue)

assertTrue([comment], booleanValue)

assertFalse([comment], booleanValue)

assertEquals([comment], value1, value2)

assertNotEquals([comment], value1, value2)

assertNull([comment], value)

assertNotNull([comment], value)

assertUndefined([comment], value)

assertNotUndefined([comment], value)

assertNaN([comment], value)

assertNotNaN([comment], value)

fail(comment)

2,准备好简单的测试页面:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>A Simple Test Page</title> <mce:script type="text/javascript" src="jsunit/app/jsUnitCore.js" mce_src="jsunit/app/jsUnitCore.js"></mce:script> <mce:script type="text/javascript" src="JavaScripts/Sample.js" mce_src="JavaScripts/Sample.js"><!-- // --></mce:script> <mce:script type="text/javascript"><!-- function setUp() { document.getElementById("value1").value = "2"; document.getElementById("value2").value = "2"; } function testValidArgs() { assertEquals("2 + 2 should equal 4", 4, addNumbers()); } function addNumbers() { var val1 = document.getElementById("value1").value; var val2 = document.getElementById("value2").value; return addTwoNumbers(val1, val2); } function tearDown() { document.getElementById("value1").value = ""; document.getElementById("value2").value = ""; } function exposeTestFunctionNames() { var tests = new Array(1); tests[0] = "testValidArgs"; return tests; } // --></mce:script> </head> <body> <input type="text" size="3" id="value1"/> <input type="text" size="3" id="value2"/> <input type="button" value="Add" onclick="addNumbers()"/> This is a simple test page for addTwoNumbers(value1, value2). </body> </html>

3,打开testRunner.html文件输入测试页面进行测试。

JsUnit支持很多方法setUp() tearDown() setUpPage()等,读完这些后,加深了对已经做自动化测试的理解。

测试结果:


二:JsUnit同时也支持JS跟踪。跟踪方法有

warn(message, [value])

inform(message, [value])

debug(message, [value])

script language="JavaScript"> function addTwoNumbers(value1, value2) { warn("this is a warning message"); warn("this is a warning message with a value", value1); return value1 + value2; } function testValidArgs() { inform("this is an inform message"); assertEquals("2 + 2 is 4", 4, addTwoNumbers(2, 2)); } function testWithNegativeNumbers() { debug("this is a debug message"); assertEquals("negative numbers: -2 + -2 is -4", -4, addTwoNumbers(-2, -2)); } </script>

 

你可能感兴趣的:(JavaScript,html,function,测试,input,Numbers)