Qunit series-3. qunit introduction (Part 1)

Source: Internet
Author: User

Automated Testing Software is a very important tool for development, and unit testing is a basic component of automated testing: Each component or unit of the software can be without human intervention, run the test tool repeatedly. In other words, you can write a test and execute it multiple times at no extra cost.

In addition to the benefits of test coverage, the test can also guide the software design, which is TDD (based on the test-driven design): first there is a test, then there is a development code. You start to write a simple test, then write the implementation code and ensure that the Code passes the test. After completing the above steps, extend your test to cover more design functions, and then write the implementation code. Repeat the above steps until the development is completed, and you will find that your implementation code is very different from the previous version.

Unit Tests in JavaScript are no different from those in other languages. You need a small framework that provides the test runner. It also provides a tool for writing test cases.

 

Automated unit testing problems

You want to automatically test your applications and frameworks, or even use TDD development methods. You may think about a testing framework of your own, but it requires a lot of extra work, involving too much details, and you also need to deal with the Javascript testing problem in different browsers.

Solution

Now there are many JavaScript unit test frameworks. For example, you can choose qunit. Qunit is a unit test framework used by jquery and has been widely used in different projects. Using qunit is simple. You only need to add two related files to your HTML page. Qunit includes qunit. JS: The test runtime and the test framework. qunit.css: the CSS file used to display the test result on the test page.

<!DOCTYPE html>

Open the above file in the browser and the result is as follows:

The only tag required is <body> containing id = "qunit-fixture" <div>, which is required for all qunit tests, even if the DIV element is empty, he provides Fixture for the test, which will be detailed in "keep test atomicity.

The interesting part is the script tag behind the test runner (qunit. JS), which contains a test method. It contains two parameters. The first parameter is of the string type, indicating the test name. It will be displayed on the test result and method. The second parameter is a function that contains the actual test code. It contains one or more assertions. The preceding example contains two assertions: OK () and equal (). We will describe in detail in the "assertion result.

We noticed that document-ready is not used here. This time, because the test runner adds test () to the test queue, the test routine is delayed.

Discussion

The page name is displayed in the test suite's header. Green bars are displayed when all tests pass. red bars are displayed when at least one test fails. There is a selection box for filtering results, and a blue bar for displaying browser information. The selection box contains "Hide passed tests". When there are many tests, you can use it to hide successful tests and only show failed tests.

Select"NoglobalsQunit lists all properties of the window at the beginning and end of each test, and compares the differences. If an attribute is added or deleted, the test fails and the difference information is displayed. In this way, we can verify that our test code and tested Code do not expose any global attributes.

The "notrycatch" selection box tells qunit not to run the test using try-catch. When an exception is thrown, the test runner stops running. However, you will get an internal exception, which will be helpful when we use an old browser (such as IE6) for testing.

The test summary is displayed under the header, showing the total number of successful and failed tests during the test. When the test is still running, it will show which test case is being executed.

The main part of the page is the test result. Each object starts with a name followed by the number of failures, number of successes, and total number of assertions. Clicking an object will display every asserted, and the expected value and actual value will often be displayed. The last "Rerun" link will run the test entity separately.

 

Assertion results

The actual elements of any unit test are assertion. The testing developer needs to use the testing framework to compare the expected values with the actual values obtained from the running test.

Solution

Qunit provides three assertions.

OK (truthy [, message])

OK () is the most basic method. It only needs one parameter. If the parameter is true, the assertion succeeds. Otherwise, the operation fails. In addition, he accepts additional string parameters for displaying test results.

test( "ok test", function() {  ok( true, "true succeeds" );  ok( "non-empty", "non-empty string succeeds" );   ok( false, "false fails" );  ok( 0, "0 fails" );  ok( NaN, "NaN fails" );  ok( "", "empty string fails" );  ok( null, "null fails" );  ok( undefined, "undefined fails" );});

 

Equal (actual, expected [, message])

The EQUAL () method uses a simple comparison operator (=) to compare the expected value and the actual value. When they are equal, the assertion succeeds. Otherwise, the assertion fails. When a failure occurs, both the expected value and actual value are displayed, and the message is also displayed.

test( "equal test", function() {  equal( 0, 0, "Zero; equal succeeds" );  equal( "", 0, "Empty, Zero; equal succeeds" );  equal( "", "", "Empty, Empty; equal succeeds" );  equal( 0, 0, "Zero, Zero; equal succeeds" );   equal( "three", 3, "Three, 3; equal fails" );  equal( null, false, "null, false; equal fails" );});

Using OK () and equal () makes it easier for us to find the failed test, because when the test fails, it will clearly tell us which value causes the problem. You can use strictequal () when you need to use strict comparison (= ().

 

Deepequal (actual, expected [, message])

Deepequal () can be used as equal (), but it applies to more scenarios. Instead of using a simple comparison character (=), it uses a more precise comparison character (= ). In this case, undefined is not equal to null, 0, or an empty string (""). He also compares the object content,{Key: Value} equals {Key: Value}, or even two objects compared have different instances. Deepequal () also processes Nan, dates, regular expressions, arrays, and functions, while equal () only checks object instances.

test( "deepEqual test", function() {  var obj = { foo: "bar" };   deepEqual( obj, { foo: "bar" }, "Two objects can be the same in value" );});

If you do not want to explicitly compare the content of two objects, you can still use equal (), but deepequal () is a better choice.

 

Synchronous callback

Sometimes your code may block the execution of callback assertions, resulting in testing failure without any sound.

Solution

Qunit provides a special assertion that defines the total number of assertion contained in the test. When the test ends, the total number of assertions is not equal. No matter the execution of other assertions, failure is returned. It is also quite simple to use. When testing starts, you only need to pass the expected number of assertions as the method parameter.

test( "a test", function() {  expect( 2 );   function calc( x, operation ) {    return operation( x );  }   var result = calc( 2, function( x ) {    ok( true, "calc() calls operation function" );    return x * x;  });   equal( result, 4, "2 square equals 4" );});

Another way is to pass the expected assertion number as its second parameter to test ():

test( "a test", 2, function() {   function calc( x, operation ) {    return operation( x );  }   var result = calc( 2, function( x ) {    ok( true, "calc() calls operation function" );    return x * x;  });   equal( result, 4, "2 square equals 4" );});

Instance:

test( "a test", 1, function() {  var $body = $( "body" );   $body.on( "click", function() {    ok( true, "body was clicked!" );  });   $body.trigger( "click" );});

 

Asynchronous callback

Although reverse CT () is helpful for Synchronous callback testing, it cannot be used to handle asynchronous callback testing. asynchronous callback and the execution of execution queues in the test runner conflict. When a timeout, interval, or Ajax request is executed in the test code, the test runner continues to execute the remaining code of the test case, and then executes the remaining use cases in the test queue, instead of performing asynchronous operations.

Solution

Instead of test (), we will use asynctest (). When your test code is ready to continue, execute start ().

asyncTest( "asynchronous test: one second later!", function() {  expect( 1 );   setTimeout(function() {    ok( true, "Passed and ready to resume!" );    start();  }, 1000);});

Instance:

asyncTest( "asynchronous test: video ready to play", 1, function() {  var $video = $( "video" );   $video.on( "canplaythrough", function() {    ok( true, "video has loaded and is ready to play" );    start();  });});

 

 

Source: http://qunitjs.com/cookbook/

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.