Javascript testing tool abut v2

Source: Internet
Author: User
Tags hasownproperty

based on comments from everyone, this version has made many improvements, such as optimization of annotation extraction, support for script tags, and real-time testing.

// Dom. abut V2 (annotations-based unit testing by situ zhengmei) // http://www.cnblogs.com/rubylouvre/archive/2010/11/08/1868638.html (function () {// ecma262 new extension if (! Object. keys) {VaR _ dontenum = ['propertyisenumerable', 'isprototypeof ', 'hasownproperties', 'tolocalstring', 'string', 'value', 'constructor']; for (var I in {tostring: 1}) _ dontenum = false; object. keys = function (OBJ) {// ecma262v5 15.2.3.14 var result = [], dontenum = _ dontenum, length = dontenum. length; For (var key in OBJ) if (obj. hasownproperty (key) {result. push (key)} If (dontenum) {While (Leng Th) {key = dontenum [-- length]; If (obj. hasownproperty (key) {result. Push (key) ;}} return result ;}} if (! String. prototype. trim) {string. prototype. trim = function () {return this. replace (/^ [\ s \ xa0] + | [\ s \ xa0] + $/g, '') ;}} if (! String. prototype. quote) {string. prototype. quote = (function () {var meta = {'\ B': '\ B', '\ t':' \ t', '\ N ': '\ n',' \ F': '\ F',' \ R': '\ R ','"':'\\"', '\': '\'}, Reg =/[\ "\ x00-\ x1f]/g, regfn = function () {var c = meta [a]; return typeof c = 'string '? C: '\ U' + ('000000' +. charcodeat (0 ). tostring (16 )). slice (-4) ;}; return function () {return '"' + this. replace (Reg, regfn) + '"' ;}}) () ;}var addevent = (function () {If (document. addeventlistener) {return function (El, type, FN) {el. addeventlistener (type, FN, false) ;};} else {return function (El, type, FN) {el. attachevent ('on' + type, function () {return fn. call (El, window. event );});} }) (); Var applyif = function (target, source) {for (VAR name in source) if (! Target [name]) {target [name] = source [name];} return target ;}// release the namespace Object window. DOM = Window. dom | {}; applyif (DOM, {// http://www.cnblogs.com/rubylouvre/archive/2010/01/20/1652646.html type: (function () {var Reg =/^ (\ W)/, regfn = function ($, $1) {return $1. touppercase ()}, to_s = object. prototype. tostring; return function (OBJ, STR) {var result = (typeof OBJ ). replace (Reg, regfn); If (result = 'o Bject '| (result = 'function' & obj.exe C) {// type/I/in Safari Chrome is function if (OBJ = NULL) result = 'null'; // object, function, null, undefined, window, arguments, and so on are all the constructors named else if (obj. window = OBJ) Result = 'window'; else if (obj. callee) Result = 'arguments '; else if (obj. nodetype = 9) Result = 'document'; else if (obj. nodename) Result = (obj. nodename + ''). replace ('#', ''); // process the Element Node else if (! OBJ. constructor |! (OBJ instanceof object) {If ("send" in OBJ & "setRequestHeader" in OBJ) {// process the Host Object and node set for the IE5-8 result = "XMLHttpRequest"} else if ("length" in OBJ & "item" in OBJ) {result = "nameditem" in OBJ? 'Htmlcollect': 'nodelist';} else {result = 'unknown ';} else result = to_s.call (OBJ ). slice (8,-1);} If (result = "Number" & isnan (OBJ) Result = "Nan "; // The to_s of htmlcollection and nodelist in Safari chrome are "nodelist". This bug has no solution for the moment if (STR) {return STR === result;} return result ;}}) (), oneobject: function (array, Val) {var result = {}, value = Val! = Void 0? VAL: 1; for (VAR I = 0, n = array. length; I >>> "); If (segment. indexof (" >>>> ")! =-1) {// here El is not used. length = 2 is to avoid IE's split bug bigclosure (ELS [0], resolving, OBJ); If (ELS [1]) {smartclosure (ELS [1], resolving, OBJ) ;}} else {smartclosure (ELS [0], resolving, OBJ) ;}// construct the unit test system UI var ul = document. createelement ("Ul"); abut. el = ul; target. appendchild (UL); ul. classname = "dom-abut-result"; abut. render ("dom-abut-title", 'total '+ obj. count + 'tests '); Abut. recoder = Document. getelementbyid (abut. ulid); If (! Arguments. callee. First) {// ensure Code Execute arguments only once. callee. first = true; addevent (target, "click", function (e) {var target = e.tar GET | E. srcelement; If (target. classname = "dom-abut-slide") {var BLOCKQUOTE = target. parentnode. getelementsbytagname ("BLOCKQUOTE") [0]; If (BLOCKQUOTE) {BLOCKQUOTE. style. display = !! (BLOCKQUOTE. offsetheight | BLOCKQUOTE. offestwidth )? "None": "Block" ;}}}); // Add a style Dom. addsheet (". dom-abut-result {\ border: 5px solid # 00a7ea; \ padding: 10px; \ Background: # 03c9fa; \ list-style-type: None ;\}\. dom-abut-result Li {\ padding: 5px; \ margin-bottom: 1px; \ font-size: 14px ;\}\. dom-abut-slide {\ cursor: pointer ;\}\. dom-abut-result Li BLOCKQUOTE {\ margin: 0; \ padding: 5px; \ Display: None ;\}\. dom-abut-title {\ Background: #008000 ;\}\. dom-abut-P Ass {\ Background: # a9ea00 ;\}\. dom-abut-unpass {\ Background: red; \ color: # fff ;\}\. dom-abut-log {\ Background: # c0c0c0 ;\}\. dom-abut-log BLOCKQUOTE {\ Background: #808080 ;\} ") ;}try {abut. ismodify & eval (uneval); EVAL (resolving. join ("");} catch (e) {return abut. render ("dom-abut-unpass", "failed to parse and compile the test code") ;}for (VAR I = 0, FN; fn = abut. closures [I ++];) {try {fn ();} catch (e) {abut. render ("dom-abut-UNP Ass "," th "+ FN. linenumber + "failed row test code execution") ;}} applyif (DOM, {abut: function (OBJ) {var key = obj. selector | obj. URL, target = obj.tar GET | document. body, STR; If (Dom. type (target, "string") {target = document. getelementbyid (target);} If (obj. selector) {var El = document. getelementbyid (key); If (! El) throw "can not find the target element"; STR = el. text;} else {var xhr = Dom. xhr (); xhr. open ("get", key + "? "+ (New date-0), false); xhr. Send (null); STR = xhr. responsetext |" "; if (! Str) throw "the target file does not exist";} evalcode (STR, target)}, getcomments: function (text) {var M, result = []; while (M = rcomments.exe C (text) {result. push (M [1] | M [2]). replace (rstar, function ($, $1) {return $1});} return result. join ('\ n') ;}, addsheet: function (CSS) {If (! -[1,]) {CSS = CSS. replace (ropacity, function ($, $1) {$1 = parsefloat ($1) * 100; if ($1 100) Return "; Return" filter: alpha (opacity = "+ $1 +"); "}) ;}css + =" \ n "; // Add line breaks at the end to facilitate viewing in firebug. VaR Doc = Document, head = Doc. getelementsbytagname ("head") [0], Styles = head. getelementsbytagname ("style"), style, media; If (! Styles. length) {// If the style element does not exist, create style = Doc. createelement ('style'); style. setattribute ("type", "text/CSS"); head. insertbefore (style, null)} style = styles [0]; media = style. getattribute ("Media"); If (Media === null &&! /Screen/I. test (media) {style. setattribute ("Media", "all");} If (style. stylesheet) {// ie style.stylesheet.css text + = CSS; // Add a new internal style} else if (Doc. getboxobjectfor) {style. innerhtml + = CSS; // Firefox supports adding style sheet strings directly to innerhtml} else {style. appendchild (Doc. createtextnode (CSS) }}, // compare whether the object is equal or similar to isequal: function (a, B) {if (a = B) Return true; vaR Atype = typeof (A), btype = typeof (B); If (Atype! = Btype) return false; if (a = B) Return true; If ((! A & B) | (&&! B) return false; if (. isequal) return. isequal (B); If (Dom. type (a, "date") & Dom. type (B, "date") return. valueof () = B. valueof (); If (Dom. type (a, "Nan") & Dom. type (B, "Nan") return false; If (Dom. type (a, "Regexp") & Dom. type (B, "Regexp") return. source = B. source &. global = B. global &. ignorecase = B. ignorecase &. multiline = B. multiline; If (Atype! = 'Object') return false; If (A. Length & (A. length! = B. Length) return false; var akeys = object. Keys (A), bkeys = object. Keys (B); If (akeys. length! = Bkeys. Length) return false; For (var key in a) if (! (Key in B) |! Dom. isequal (A [Key], B [Key]) return false; return true ;}, inspect: function (OBJ, indent) {indent = indent | ""; if (OBJ = NULL) return indent + "null"; if (OBJ = void 0) return indent + "undefined"; if (obj. nodetype = 9) return indent + "[object document]"; if (obj. nodetype) return indent + "[object" + (obj. tagname | "Node") + "]"; var arr = [], type = Dom. type (OBJ), Self = arguments. callee, next = indent + "\ t"; Switch (type) {Case "Boolean": Case "Number": Case "Nan": Case "Regexp ": return indent + OBJ; Case "string": Return indent + obj. quote (); Case "function": Return (indent + OBJ ). replace (/\ n/g, "\ n" + indent); Case "date": Return indent + '(new date (' + obj. valueof () + ')'; Case "unknown": Case "XMLHttpRequest": Case "window": Return indent + "[object" + Type + "]"; case "nodelist": Case "htmlcollection": Case "arguments": Case "array": For (VAR I = 0, n = obj. length; I '+ arguments. callee. linenumber + "line log" + (Message | "") + ""; var testcode ="
"+ DOM. Inspect (OBJ) +"

";
This. Render ("dom-abut-log", context, testcode );
},
Preparerender: function (bool, linenumber, testcode ){
VaR classname = bool? 'Dom-abut-pass': 'dom-abut-unpass ',
Context ='Line '+ linenumber +' test code: '+ (bool? 'Pass': 'pass') +"";
This. recoder. innerhtml = "completed" + (++ this. Time) + "tests ";
This. Render (classname, context, testcode );
},
Render: function (classname, context, code ){
VaR li = Document. createelement ("Li ");
Li. classname = classname;
This. El. appendchild (LI );
VaR BLOCKQUOTE = Document. createelement ("BLOCKQUOTE ")
Li. innerhtml = context;
If (CODE ){
Li. appendchild (BLOCKQUOTE );
BLOCKQUOTE. innerhtml = code;
}
}
});
})();

Test Example 1:

 
VaR test1 = 1;/*** <* $ log () * >>>> * // * dsfds * // frgtretr/*** erwwer **/

<Br/> var source = document. getelementbyid ("test1 "). innerhtml; <br/> alert (source); <br/> alert (Dom. getcomments (source) <br/>

Run code

Test Example 2:

VaR P = function () {}// comment/* not-a-nested-Comment P ('not-a-comment '); // comment */* still-a-Comment P ('not-a-comment');/* alert ('commented-out-Code '); // still-a-Comment */P ('not-a-comment'); var Re = // \/* not-a-Comment */; // * Comment

<Br/> var source = document. getelementbyid ("Test2 "). innerhtml; <br/> alert (source); <br/> alert (Dom. getcomments (source) <br/>

Run code

Abut V2 adds support for scripts. For this method, the parameter is changed from a string to a hash. The Hash has three values: selector, URL, and target. Selector refers to the ID of the script tag. It is obtained through innerhtml for testing. URL refers to the path of the JS file. We get responsetext by synchronizing Ajax requests for testing. Because it is an Ajax request, it will be restricted by the same-origin policy. Therefore, I cannot release the example in V1, therefore, the selector method will be used in subsequent examples. Target refers to the element node in which the test result is put. The default value is document. body. This parameter is optional. If it is a string, it is automatically searched as the tag ID.

For example, if there is a script element node with ID test3 on my page, its innerhtml is as follows:

 
VaR person = function (name, sex) {This. name = Name; this. sex = sex; // #### log (this. name); // #### log (this. sex);} var P = new person ("Ruby", "Louvre ");

To test it, you just need to reference abut. js and run the following script on the page:

 
Dom. abut ({selector: ID, // script tag to be tested // URL: URL, // only the path of the same domain is limited to target: document. body // position to which the test result is added (it can be an element node or its id value )});

Run code

In this example, we can also see the new identifier ####, which will replace the original @@@@. @ In V1 aims to release the data in the closure or internal function to the global scope, and then test it with a series of methods $. Then, practice has proved that this is a little troublesome. Why not execute it directly in the original internal scope ?! #### It is developed for this purpose. Correspondingly, it is useless when @ is used. It is discarded and removed by me. #### The source code will be modified and then interpreted and executed, while $ will parse and execute the source code before repairing the test sample in the annotation, the execution time is totally different. $ It can be the same as EQ, same, OK, and log functions, but #### it cannot be written between >>>.

Example 4: Use of multi-line test comments.

 
VaR flatten = function (ARR) {var result = [], self = arguments. callee; For (VAR I = 0, n = arr. length, El; I >> */

Run code

Example 5 (the base module that intercepts the self-Framework)

VaR proto = "prototype", ctor = "constructor", hasown = object [proto]. hasownproperty; // the type used to obtain data or determine the data type. // $ (Dom. type (1, "Number"); // $ (Dom. type (Nan, "Nan"); // $ (Dom. type (void (0), "undefined"); // $ (Dom. type ("AAA", "string"); // $ (Dom. type ([1, 2, 3], "array"); // $ (Dom. type (/I/, "Regexp"); // $ (Dom. type ({}, "object"); // $ (Dom. type (document, "document"); // $ (Dom. type (d Ocument. body, "body"); // $ (Dom. type (window, "window"); // $ (Dom. type (true, "Boolean"); // $ (Dom. type (document. getelementsbytagname ('script'), "htmlcollection"); Dom. type = (function () {var Reg =/^ (\ W)/, regfn = function ($, $1) {return $1. touppercase ()}, to_s = object [proto]. tostring; return function (OBJ, STR) {var result = (typeof OBJ ). replace (Reg, regfn); If (result = 'object' | (resul T = 'function' & obj.exe C) {// type/I/in Safari chrome: function if (OBJ = NULL) Result = 'null '; else if (obj. window = OBJ) Result = 'window'; // return the window constructor name else if (obj. callee) Result = 'arguments '; else if (obj. nodetype = 9) Result = 'document'; else if (obj. nodename) Result = (obj. nodename + ''). replace ('#', ''); // process the Element Node else if (! OBJ. constructor |! (OBJ instanceof object) {If ("send" in OBJ & "setRequestHeader" in OBJ) {// process the Host Object and node set for the IE5-8 result = "XMLHttpRequest"} else if ("length" in OBJ & "item" in OBJ) {result = "nameditem" in OBJ? 'Htmlcollect': 'nodelist';} else {result = 'unknown ';} else result = to_s.call (OBJ ). slice (8,-1);} If (result = "Number" & isnan (OBJ) Result = "Nan "; // The to_s of htmlcollection and nodelist in Safari chrome are "nodelist". This bug has no solution for the moment if (STR) {return STR === result;} return result ;}}) () // generate an object with unified key values for high-speed judgment // $ same (Dom. oneobject (["AA", "BB", "cc"]), {"AA": 1, "BB": 1, "cc": 1}) Dom. oneobject = function (ARR Ay, Val) {var result = {}, value = Val! = Void 0? VAL: 1; for (VAR I = 0, n = array. length; I

run the Code

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.