Proficient in Javascript Chapter 4: Debugging and testing tools

Source: Internet
Author: User
Maybe you are using any Programming Language The most time-consuming part of development is testing and debugging. Code . For Professional-level code, make sure that what you write is fully tested, verifiable, and zero bug, and become extremely important. One aspect that makes JavaScript so different from other programming languages is that it is not owned and supported by any individual company or organization (unlike C #, PHP, Perl, Python, or Java ). This difference makes it extremely challenging to have the same foundation for debugging and testing code.
To reduce the workload and pressure you may have to endure, many powerful development tools are available when JavaScript errors are captured. Each modern browser has its own (quality-compatible) tool. Using them will make Javascript development more consistent and promising.

In this chapter, I will discuss different tools for debugging JavaScript code, and then build reliable and reusable Test suites to test future development.

Debugging

Testing and debugging are two inseparable links. When you create a wide range of test cases for your code, you will surely encounter some strange errors that require attention. This is where the debugging process is used. Learn how to use the best available tools to find and fix youProgramCan ensure that your code runs faster.

Error Console
The easiest tool available in most modern browsers is some form of error console. The quality of the console, the accessibility of the interface, and the quality of error messages vary greatly across different browsers. In the end, you may be better off using a browser with the most suitable developer error Console (or other plug-ins for debugging) to start your debugging process.

Internet
Explorer

 
Having the most popular browser doesn't mean having the best debugging tool. Unfortunately, the error console of IE has serious shortcomings. One problem is that the console is disabled by default. If you do not use IE as the default browser (it is highly suspected that any self-respecting JavaScript developers will do this ), this will make the wrong search more confusing.
In addition to the availability mentioned above, the most troublesome problem with the IE error console is the following:
A.
Only one error is displayed at a time. You must rely on the menu system to find other errors.
B.
The meaning of the error message is rather vague and has almost no logic significance. They rarely provide a precise description of the problem.
C.
The reported error is always offset by one row, that is, the actual error row number is always one smaller than the reported error. This is combined with vague errors, and you may suffer from bugs.
Figure 4-1 shows an example of the IE error console when an error occurs.

4-1.gif (7.01 KB)

 
Figure 4-1.javascript error console in IE

 
As I mentioned at the beginning of this section, it may be a good idea to start your JavaScript debugging process in another (non-ie) browser. Once you have completely cleared all bugs in that browser, you should be able to easily locate the intricate issues that occur in IE.

Firefox

Over the past few years, Firefox has made great progress in Ui, helping web developers develop better websites more easily. The javascript error console has been updated many times and has produced some useful things.
A.
The console allows you to enter arbitrary Javascript commands. This is used to determine the value of a variable after the page is loaded.
B.
The console provides the ability to classify messages based on their types (such as errors, warnings, or messages.
C.
The latest version of the console provides style sheet warnings along with JavaScript errors. Although it may provide a large number of unnecessary error messages on poorly designed websites, it is helpful to find out your own layout defects.
D.
One disadvantage of the error console is that it does not filter messages based on the page you are browsing, which means you will get a mix of errors on different pages. (The firebug plug-in I will talk about in the next section solves this problem .)
Figure 4-2 shows a screenshot of the Firefox error console. Note that you can use different buttons to switch between different types of error messages.
4-2.gif(22.49 KB)

Figure 4-2.
Firefox Javascript error Console

Although the Firefox error console is very good, it is not perfect. Because of this, developers tend to turn to various Firefox plug-ins to better debug their applications. I will discuss these plug-ins later.

Safari

Safari is one of the latest browsers on the market and also a fast growing browser. As a result, its JavaScript support (both during development and execution) is sometimes unstable. In this case, it is difficult to enter the Javascript console in the browser. It is not even an easy-to-activate option. It is completely hidden in a Debug menu that is inaccessible to general users.
To activate the debugging menu (JavaScript console), you need to execute the commands shown in 1-4 on a terminal (when Safari is not running.

Program 4-1.
Allows safari to display debugging menu commands

Copy content to clipboard

Code:

Defaults write com. Apple. Safari includedebugmenu
1

Next time you open safari, you will have a new debugging menu that contains the Javascript console options.
As you can guess from its hidden location, the console is still in a very primitive state. The Firefox error console must mention the following:
A.
The error message is generally vague, roughly at the same level as the error message of IE.
B. Provide the row number where the error is located, but it is often reset to zero, throwing you back to the place where you started.
C.
Messages are not filtered Based on the page, but all messages will be listed after the script that throws this error.
Figure 4-3 shows a screenshot of the error console running on safari2.0.
4-3.gif(14.31 KB)

Figure 4-3.
Safari Javascript error Console

As a web development platform, Safari is still far behind. However, the WebKit development team (a team that developed the safari rendering engine) is working to bring the browser to the forefront and make good progress. We look forward to many new developments in the browser in the coming months and years.

Opera

Finally, let's take a look at the error console contained in operabrowser. It is appreciated that opera has invested a lot of time and effort to make it rich and useful. In addition to all the features of the Firefox console, it also provides the following:
A.
Descriptive error messages give you a good understanding of the problem
B. Inline code snippets use the Code itself to describe the error
C.
Errors can be filtered by type (such as JavaScript, CSS, and so on)
Unfortunately, this error Console does not have the ability to execute JavaScript commands, two of the three items listed are already available in Firefox, and now a Firefox has been created but it does not), which is such a useful function. Even so, the sum up has already formed a good error console. Figure 4-4 shows a screenshot of the error console in opera9.0.
4-4.gif(23.82 KB)
11: 04

Figure 4-4.opera JavaScript error Console

Opera has been taking web development seriously for a long time. The development team has many active and energetic developers and document writers. The opera platform has been striving to better serve web developers.

Dom Viewer

Dom viewing is one of the most useful and underutilized tools for JavaScript developers. Dom viewing can be viewed as a pageSource codeView an advanced version that allows you to view the current status of the page after the content of your code is modified.
Different Dom viewers in each browser have different behaviors. Some provide additional functions that allow you to deeply observe the objects you are operating on. In this section, I will introduce three different browsers and discuss what makes them very different from each other.

Firefox Dom Viewer

The Dom viewer of Firefox is a Firefox plug-in pre-contained in all Firefox installation packages (but not installed by default ). This plug-in allows you to navigate to HTML documents after they are created and operated. A screenshot of this plug-in is shown in Figure 4-5.
4-5.gif(94.11 KB)

Figure 4-5.
Firefox built-in Dom Viewer

When navigating a document, you can not only view the structure of the modified HTML element, but also view the style attributes of each element and their object attributes. This helps you know exactly what the webpage looks like after modification. This makes the viewer an essential tool.

Safari Web Viewer

Safari has a new Dom viewer included in the latest version of its browser. In some ways, it is better than Firefox's Dom viewer. You can right-click any element of the page so that the viewer can immediately navigate to it. Figure 4-6 shows (elegantly designed) Safari
A screenshot of the DOM viewer.
4-6.gif(52.34 KB)
11: 04

Built-in Dom viewer in Safari

Although this plug-in is included in the latest Safari version, activating it is even more troublesome than the Javascript console mentioned above. This fact is hard to understand: why have the safari team made so much effort to write and add these components, and finally hidden them from developers who want to use them. Regardless of this, in order to activate the DOM viewer, you must execute the statement shown in program 4-2.

Program 4-2.
Activate the safari Dom Viewer

Copy content to clipboard

Code:

Defaults write com. Apple. Safari webkittings extras
-Bool
True

The Dom viewer of safari still needs to be developed and improved in many places. Fortunately, the development team of Safari is very talented. However, it is recommended that you use Firefox as the basis for your development until Safari is completely completed and released.

View
Rendered Source

Finally, I want to introduce the most available Dom viewer for Web developers. Firefox plug-in view rendered
Source adds a menu item for selection under the common check source code option to provide you with a complete representation of the new HTML document in an intuitive and understandable way. For more information about this plug-in, visit http://javasermadden.com /.
In addition to providing a very natural source code view, it also provides hierarchical code coloring for each layer of the document, allowing you to better feel where you are in the code. See Figure 4-7.
4-7.gif(24.91 KB)

Figure 4-7. Firefox plug-in view
Rendered Source

View rendered
The Source Plug-in should be a standard tool for every Web Developer toolbox. Its basic purpose is far beyond the original source code view given, while still allowing more complex Firefox
Smooth upgrade of the DOM viewer plug-in.

Firebug

Joe
The firebug created by Hewitt is one of the most important Javascript development plug-ins in recent years. As a complete Javascript development kit, it has an error console, a debugger, and a DOM viewer. For more information about this plug-in, visit http://www.joehewitt.com/software/firebug /.
One of the major advantages of combining so many tools is that you can better infer where the problem is. For example, when you click an error message, the Javascript file name and the row number of the error will be displayed to you. Therefore, you can set breakpoints and intervene in code execution to better understand the problems. A screenshot of this plug-in is shown in Figure 4-8.
4-8.gif(25.06 KB)

Figure 4-8.
Firebug debugging plug-in

So far, the development of modern debugging tools has not seen any better than firebug. I strongly recommend that you use Firefox as your basic Javascript development platform and use the firebug plug-in together.

Venkman

The last piece of the Javascript development puzzle is the Venkman
Extension (do not know where to start puzzle ). As part of the Mozilla browser, verkman is the code name of the Javascript debugger project initiated by Mozilla. For more information about this project and the updated Firefox plug-in, you can find it on the following website:
Mozilla's Venkman project:Http://www.mozilla.org/projects/venkman/
Venkman plug-in of Firefox:Https://addons.mozilla.org/firefox/216/
Venkman Tutorial:Http://www.mozilla.org/projects/venkman/venkman-walkthrough.html
The importance of using such a plug-in is that, due to its deep integration with the JavaScript engine itself, it allows you to have more advanced control over what the code is doing. Figure 4-9 is a screenshot of Firefox's vernkman plug-in.
4-9.gif(85.57 KB)

Figure 4-9.
Popular JavaScript debugger Venkman with Firefox APIs

With all the additional control introduced by this plug-in, apart from entering the code analysis and execution process, you can also know exactly what variables are available to you in a scope and the exact information about attributes or variable states.

Test(Because I don't know much about code testing, the translation of the content in this section is very reluctant. Please forgive me)

Personally, I think of the test process and the creation of test cases as "[color] future-proofing (not coming up with a proper word to express it)" your code. Creating reliable test cases for your basic code or library saves you countless times to debug code and find weird bugs that you inadvertently introduce during debugging.
This is a common practice in most modern programming environments and has a set of reliable test cases, it not only helps you, but also helps others who use your code library to add new features and fix errors.
In this section, I will introduce three different libraries that can be used to build a javascript test suite. They can all be executed in a cross-browser, automated manner.

Jsunit

Jsunit has long been the prime standard for JavaScript unit testing. Most of its functions are based on the popular JUnit package designed for Java, which means you can easily use this library if you are familiar with how JUnit works through Java. Its site (http://www.jsunit.net/) has plenty of available information and documentation (http://www.jsunit.net/documentation ).
Like most (at least all I have discussed in this section) Test suites, they consist of three basic components:
Test
Runner): This part of the suite provides a good graphical output to show which stage has been run to all operations. It provides the ability to load test groups and parallel content, recording all the outputs they provide.
Test
Suite): This is a collection of all test cases (sometimes distributed across multiple webpages.
Test
Cases): This is an independent command that can evaluate to a true/false expression. It gives you measurable results to determine whether your code works correctly. A separate test case may not be very useful, but when used together with the test runner, you will get a useful interactive experience.
All of these constitute a comprehensive automated test suite that can be used to run and join future tests. Program 4-3 shows a simple test group, and program 4-4 is a set of test cases.

Code 4-3.
Test Group created using jsunit

Copy content to clipboard

Code:

<HTML>
<Head>
<Title> jsunit Test
Suite </title>
<Script
Src = "../APP/jsunitcore. js"> </SCRIPT>
<SCRIPT>
Function
Suite (){
VaR newsuite = new
Top. jsunittestsuite ();
Newsuite. addtestpage ("jsunittests.html ");
Return
Newsuite;
}
</SCRIPT>
</Head>
<Body> </body>
</Html>

Program 4-4.
Jsunit can be used for various test cases on typical test pages

Copy content to clipboard

Code:

<HTML>
<Head>
<Title> jsunit
Assertion tests </title>
<Script
Src = "../APP/jsunitcore. js"> </SCRIPT>
<SCRIPT>
// Test whether an expression is true.
Function
Testasserttrue (){
Asserttrue ("True shocould be true ",
True );
Asserttrue (true );
}
// Test whether an expression is false.
Function
Testassertfalse (){
Assertfalse ("false shocould be false ",
False );
Assertfalse (false );
}
// Check whether two parameters are equal
Function
Testassertequals (){
Assertequals ("1 shoshould equal 1", 1,
1 );
Assertequals (1, 1 );
}
// Check whether two parameters are not equal
Function
Testassertnotequals (){
Assertnotequals ("1 shocould not equal 2", 1,
2 );
Assertnotequals (1, 2 );
}
// Test whether the parameter is null
Function
Testassertnull (){
Assertnull ("null shocould be null ",
Null );
Assertnull (null );
}
// Check if the parameter is not null
Function
Testassertnotnull (){
Assertnotnull ("1 shocould not be null ",
1 );
Assertnotnull (1 );
}
</SCRIPT>
</Head>
<Body> </body>
</Html>

The documentation for jsunit is very good, and because it has been around for a long time, you are very hopeful to find a good example of practical application.

J3unit
J3unit is a new recruit in Javascript unit testing. This particular Library provides a function that surpasses jsunit in that it can be integrated directly with server-side Test suites (such as JUnit or jetty. This may be extremely useful for JavaScript developers because they can quickly traverse all test cases for their client and server code at the same time. However, since not everyone uses Java, j3unit also provides a static mode that can be executed in your browser like other unit testers. More information about j3unit can be found on its website: http://j3unit.sourceforge.net]/.
Because it is rare to check the server code and client test cases, let's take a look at how the static client test unit of j3unit works. Fortunately, they are actually no different from other test kits, which makes porting very simple. As shown in code 4-5 of the program.

Program 4-5.
Simple Test executed using j3unit

Copy content to clipboard

Code:

<HTML>
<Head>
<Title> sample
Test </title>
<SCRIPT src = "JS/unittest. js"
Type = "text/JavaScript"> </SCRIPT>
<SCRIPT src = "JS/suiterunner. js"
Type = "text/JavaScript"> </SCRIPT>
</Head>
<Body>
<P
Id = "title"> sample test </P>
<Script
Type = "text/JavaScript">
New
Test. Unit. Runner ({
// Test the display and display elements
Testtoggle: function () {with (this)
{
VaR Title =
Document. getelementbyid ("title ");
Title. style. Display =
'None ';
Assertnotvisible (title, "title shocould be
Invisible ");
Element. style. Display =
'Block ';
Assertvisible (title, "title shoshould be
Visible ");
}},

// Add one element to another
Testappend:
Function () {with (this ){
VaR Title =
Document. getelementbyid ("title ");
VaR P =
Document. createelement ("p ");
Title. appendchild (P
);
Assertnotnull (title. lastchild );
Assertequal (
Title. lastchild, P
);
}}
});
</SCRIPT>
</Body>
</Html>

Jsunit, despite being quite new, has demonstrated the bright future of the unit test framework. If you are interested in the object style, I recommend you try it.

Test. Simple

The last example of JavaScript unit testing is another newcomer. Test. Simple is introduced by the creation of JSAN and serves as a way to standardize the testing of all submitted JavaScript modules. Because of its wide application, test. Simple has a large number of documents and examples, which are two important aspects when using a testing framework. For more information about test. Simple (and its sister database test. More), see:
Test. Simple:

Http://openjsan.org/doc/t/th/theory/Test/Simple/

Test. Simple document:

Http://openjsan.org/doc/t/th/theory/Test/Simple/0.21/lib/Test/Simple.html

Test. More documentation:

Http://openjsan.org/doc/t/th/theory/Test/Simple/0.21/lib/Test/More.html

The test. Simple Library provides a large number of debugging methods and a complete test runner, which provides automated test execution. 4-6 is an example of a test. Simple test group.

Program 4-6.
Use test. Simple and test. More to perform the test.

Copy content to clipboard

Code:

// Load the test. More module (used to test itself)
New
JSAN ('../lib'). Use ('test. more ');
// Six tests are scheduled (so that you can know when a problem occurs)
Plan ({tests:
6 });
// Test 3 simple cases
OK (2 = 2, 'two is two is two ');
Is ("foo ",
"Foo", 'foo is foo ');
Isnt ("foo", "bar", 'foo isnt
Bar ');
// Test using regular expression
Like ("fooble",/^ Foo/, 'foo is like
Fooble ');
Like ("fooble",/Foo/I, 'foo is like
Fooble ');
Like ("/usr/local/", '^ \/usr \/local', 'regexes with slashes in like'
);

Personally, I like the simplicity of test. Simple and test. More, because they do not have much common overhead and help keep your code concise. Of course, it is too important to decide which test suite is most suitable for you, but you have to consider yourself. It is too important to choose a test suite for your 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.