Javascript unit test the abcjavascript date Formatting Function, which is similar to the method used in C #.

Source: Internet
Author: User
Preface

At present, in software development, unit testing is increasingly valued by developers. It can improve the efficiency of software development and ensure the quality of development. In the past, unit tests were often used in server development. However, with the gradual division of work in the Web programming field, related unit tests can also be carried out in the front-end Javascript development field, to ensure the quality of front-end development.

In server-side unit testing, there are various testing frameworks and some excellent frameworks in Javascript, but in this article, we will implement a simple unit test framework step by step.

JS unit testing involves many aspects, including method function check and browser compatibility check. This article focuses on the first one.

JSCodeIt is a JS date formatting method I previously wrote. The original Article is here (The javascript date Formatting Function is similar to the method used in C #. The Code is as follows:

Date. Prototype. tostring = Function  (Format ){  VaR Time = {}; Time. Year = This  . Getfullyear (); time. tyear = ("" + Time. Year). substr (2 ); Time. Month = This . Getmonth () + 1 ; Time. tmonth = Time. Month <10? "0" + Time. Month: Time. Month; time. Day = This  . Getdate (); time. tday = Time. Day <10? "0" + Time. Day: Time. Day; time. Hour = This  . Gethours (); time. thour = Time. Hour <10? "0" + Time. Hour: Time. hour; time. Hour = Time. Hour <13? Time. Hour: Time. Hour-12; Time. thour = Time. Hour <10? "0" + Time. Hour: Time. hour; time. Minute = This  . Getminutes (); time. tminute = Time. Minute <10? "0" + Time. Minute: Time. Minute; time. Second = This  . Getseconds (); time. tsecond = Time. Second <10? "0" + Time. Second: time. Second; time. millisecond = This  . Getmilliseconds ();  VaR Onumber = time. millisecond/1000;If (Format! = Undefined & format. Replace (/\ s/g, ""). length> 0 ) {Format = Format. Replace ( /YYYY/ Ig, time. Year). Replace ( /YYY/ Ig, time. Year). Replace ( /Yy/ Ig, time. tyear). Replace ( /Y/ Ig, time. tyear). Replace ( /MM/ G, time. tmonth). Replace ( /M/ G, time. month). Replace ( /DD/Ig, time. tday). Replace ( /D/ Ig, time. Day). Replace ( /Hh/ G, time. thour). Replace ( /H/ G, time. Hour). Replace ( /Hh/ G, time. thour). Replace ( /H/ G, time. Hour). Replace ( /MM/ G, time. tminute). Replace ( /M/ G, time. Minute). Replace ( /SS/ Ig, time. tsecond). Replace ( /S/Ig, time. Second). Replace ( /FFF/ Ig, time. millisecond). Replace ( /FF/ig, onumber. tofixed (2) * 100 ). Replace ( /F/ig, onumber. tofixed (1) * 10 );}  Else  {Format = Time. Year + "-" + time. Month + "-" + time. day + "+ time. Hour +": "+ time. Minute +": "+ Time. Second ;}  Return  Format ;} 

No serious bugs have been found in this Code. To test this code. Replace (/MM/G, time. tmonth). Replace (/MM/G, time. month). The error is that when the month is less than 10, the two digits are not used to represent the month.

Now there is such a sentence, good design is reconstructed, and in this article, we start from the simplest.

First version: use the original Alert

As the first version, we use alert to check the code. The complete code is as follows:

<! Doctype HTML>  Date. Prototype. tostring = Function  (Format ){  VaR Time ={}; Time. Year = This  . Getfullyear (); time. tyear = ("" + Time. Year). substr (2 ); Time. Month = This . Getmonth () + 1 ; Time. tmonth = Time. Month <10? "0" + Time. Month: Time. Month; time. Day = This  . Getdate (); time. tday = Time. Day <10? "0" + Time. Day: Time. Day; time. Hour = This . Gethours (); time. thour = Time. Hour <10? "0" + Time. Hour: Time. hour; time. Hour = Time. Hour <13? Time. Hour: Time. Hour-12 ; Time. thour = Time. Hour <10? "0" + Time. Hour: Time. hour; time. Minute = This  . Getminutes (); time. tminute = Time. Minute <10? "0" + Time. Minute: Time. Minute; time. Second = This  . Getseconds (); time. tsecond = Time. Second <10? "0" +Time. Second: time. Second; time. millisecond = This  . Getmilliseconds ();  VaR Onumber = time. millisecond/1000; If (Format! = Undefined & format. Replace (/\ s/g, ""). length> 0 ) {Format = Format. Replace ( /YYYY/ Ig, time. Year). Replace ( /YYY/ Ig, time. Year). Replace ( /Yy/Ig, time. tyear). Replace ( /Y/ Ig, time. tyear). Replace ( /MM/ G, time. month). Replace ( /M/ G, time. month). Replace ( /DD/ Ig, time. tday). Replace ( /D/ Ig, time. Day). Replace ( /Hh/ G, time. thour). Replace ( /H/ G, time. Hour). Replace ( /Hh/ G, time. thour). Replace ( /H/G, time. Hour). Replace ( /MM/ G, time. tminute). Replace ( /M/ G, time. Minute). Replace ( /SS/ Ig, time. tsecond). Replace ( /S/ Ig, time. Second). Replace ( /FFF/ Ig, time. millisecond). Replace ( /FF/ig, onumber. tofixed (2) * 100 ). Replace ( /F/ig, onumber. tofixed (1) * 10 );}  Else {Format = Time. Year + "-" + time. Month + "-" + time. day + "+ time. Hour +": "+ time. Minute +": "+ Time. Second ;}  Return  Format ;}  VaR Date = New Date ( ); Alert (date. tostring ( "YYYY" ); Alert (date. tostring ( "Mm" )); </SCRIPT> </body> 

2012 and 4 will pop up after running. We know that the date. tostring ("mm") method is faulty.

This method is inconvenient. The biggest problem is that it only prompts the results and does not provide correct or wrong information, unless you are very familiar with the code, otherwise, it is hard to know that the pop-up result is a false positive. Below, we will write an Assert method for testing, and clearly provide the false positive information.

Version 2: Check with assert

Assertions are expressionsProgramThe designer expects the system to reach the state. For example, there is a method to add two numbers. For 3 + 2, we expect the result returned by this method to be 5, if 5 is indeed returned, it will pass; otherwise, an error message will be given.

Assert is the core of unit testing and provides the asserted function in various unit testing frameworks. Here we write a simple assert method:

 
FunctionAssert (message, result ){If(!Result ){Throw NewError (Message );}Return True;}

This method accepts two parameters. The first is the prompt message after the error, and the second is the asserted result.

The following code tests with assertions:

 
VaRDate =NewDate ();Try{Assert ("YYYY shocould return full year", date. tostring ("YYYY") = "2012");}Catch(E) {alert ("Test failed:" +E. Message );}Try{Assert ("Mm shoshould return full month", date. tostring ("mm") = "04");}Catch(E) {alert ("Test failed:" +E. Message );}

The following window will pop up after running:

Third Edition: conduct a batch test

In version 2, The assert method can provide clear results, but if you want to perform a series of tests, it is not convenient to capture exceptions for each test. In addition, the number of successes, the number of failures, and the error message of failures can be provided in the general test framework.

For the convenience of viewing the test results, here we will display the results on a page with colored text, so here we need to write a small output method printmessage:

 
FunctionPrintmessage (text, color ){VaRDIV = Document. createelement ("Div"); Div. innerhtml=Text; Div. style. Color=Color; document. Body. appendchild (DIV );DeleteDiv ;}

Below, we will write a similarJstestdriverTo Perform Batch testing:

 Function  Testcase (name, tests ){  VaR Successcount = 0;  VaR Testcount = 0 ;  For ( VaR Test In  Tests) {testcount ++ ;  Try  {Tests [test] (); printmessage (Test + "Success", "#080" ); Successcount ++ ;}  Catch (E) {printmessage (Test + "Failed:" + E. message, "#800" ) ;}} Printmessage ( "Test Result:" + testcount + "tests," + successcount + "success," + (testcount-successcount) + "failures", "#800" );} 

Test code:

VaRDate =NewDate (); Testcase ("Date tostring test",{Yyyy:Function() {Assert ("YYYY shoshould return 2012", date. tostring ("YYYY") = "2012");},MM:Function() {Assert ("Mm shoshould return 04", date. tostring ("mm") = "04");},DD:Function() {Assert ("DD shoshould return 09", date. tostring ("DD") = "09");}});

Result:

In this way, we can see at a glance what went wrong. But is this perfect? We can see that VaR date = new date (,) in the last test was defined outside testcase, in addition, the entire testcase test code uses date. Here, because the value of date is not modified in each method, there is no problem. If the value of date is modified in a test method, the test results are inaccurate. Therefore, the setup and teardown methods are provided in many testing frameworks to provide and destroy test data in a unified manner, next we will add the setup and teardown methods in our testcase.

Version 4: provides a uniform batch test of test data

First, add the setup and teardown methods:

Testcase ("date tostring" , {Setup:  Function  (){  This . Date = New Date ( ) ;}, Teardown:  Function  (){  Delete  This  . Date;}, yyyy:  Function  () {Assert ( "YYYY shoshould return 2012 ", This . Date. tostring ("YYYY") = "2012" ) ;}, Mm:  Function  () {Assert ( "Mm shoshould return 04 ", This . Date. tostring ("mm") = "04" ) ;}, DD:  Function  () {Assert ( "DD shoshould return 09 ",This . Date. tostring ("DD") = "09" );}}); 

Because the setup and teardown methods are not involved in the test, we need to modify the testcase code:

 Function  Testcase (name, tests ){  VaR Successcount = 0 ;  VaR Testcount = 0 ;  VaR Hassetup = Typeof Tests. Setup = "function" ;  VaR Hasteardown =Typeof Tests. teardown = "function" ;  For ( VaR Test In  Tests ){  If (Test = "setup" | test = "teardown" ){  Continue  ;} Testcount ++ ;  Try  {  If (Hassetup) {tests. Setup () ;}tests [test] (); printmessage (Test + "Success", "#080" );  If  (Hasteardown) {tests. teardown ();} successcount ++ ;}  Catch  (E) {printmessage (Test + "Failed:" + E. message, "#800" ) ;}} Printmessage ( "Test Result:" + testcount + "tests," + successcount + "success," + (testcount-successcount) + "failures", "#800" );} 

The running result is the same as that of the third edition.

Summary and reference Article

As mentioned above, a good design is the result of continuous reconstruction. Is the fourth version perfect? It is far from reaching. Here is just an example. If you need this knowledge, you can write about the use of various testing frameworks later.

This article is just an example of the entry-level JS unit testing. It gives beginners a preliminary idea of JS unit testing. It is a valuable reference.

This article refers to the first chapter of "test-driven Javascript development" (I personally think it is not bad, I suggest it). The test cases in this book are also a time function, but it is complicated to write, it is not easy for beginners to understand.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.