JavaScript component journey (4): Test JavaScript component _ javascript skills

Source: Internet
Author: User
In this topic, we will discuss JavaScript testing to check whether the component status and working method meet expectations. We will also introduce a testing method that facilitates the compilation of test cases. The tests mentioned here are of course the use of automated testing methods, which is an important part of software quality assurance (QA.


In this topic, we will discuss JavaScript testing to check whether the component status and working method meet expectations. We will also introduce a testing method that facilitates the compilation of test cases. The tests mentioned here are of course the use of automated testing methods, which is an important part of software quality assurance (QA. For the Smart Queue introduced in this series, our testing objectives include:

  • Create a Task object: The second phase of the Code provides multiple creation methods, and you need to test the status of the object after it is created.
  • Task running sequence in Queue: We provide two ways to change the running order: priority and dependency configuration. We also need to test the impact of various configurations on the order.

For the first target, you only need to check whether the attributes of the object after creation meet expectations. We have already mentioned "as expected" many times, and Assert was designed for this purpose. To put it simply, assertions are to ensure that the expression to be tested is "true". Otherwise, the tester is notified in some way and the tester is located to locate the test case where the assertions fail.
The second goal is a little complicated. As we implement the component encoding, the sorted Queue (_sorted) Hidden in the closure, so the external is inaccessible. There are two ways to consider: (1) refactor the code, increase the code testability, and there are two reconstruction methods: (a) set the debug switch_sortedExposed to the outside. (B) add independent files and splice the code in the build mode to generate a test version. (2) The result of the test behavior is not a process. The former method is essentially in the running state of the component, and this method is only used to check the running result of the component. This topic selects the following test methods. The first test method is left for interested readers to practice :)

I personally disagree with the first method. a. Why? Let me first talk about the design concept of this task queue:

  • It is only a queue, and is only responsible for "Adjusting the task running order on demand" without paying attention to the individual details of the task. In other words, it operates the entire task, regardless of the specific behavior and performance of the task.
  • It is a secure queue. Users (the "customer" mentioned in the first phase) can add tasks with confidence without worrying that the task information will be seen by other customers. It should be noted that the second implementation code containsSmartQueue.Queue = [[], [], []]The result is that the queue items can be accessed externally. The code is only for introduction. You can delete it safely.SmartQueue.Queue = To achieve security control.

Back to the topic discussed just now, after setting the debug switch, the task information may potentially leak. Further, the code can be modified to achieve the security when the debug switch is used. The practice is to put the control of the switch in the SmartQueue constructor, this requires SmartQueue to implement the Singleton mode (see the previous article). Once an object is created, the debug tag in the closure cannot be modified.

Before writing a specific test code, we designed a test method to simplify the compilation of the test code (mainly use cases. Simply put, the test case is separated from the code of the test itself-the former is written in a good semantic manner, and the latter is written in one time to process the test case set by the former. The case writer needs to write code in the format of this:

  <ul id="J_test_cases">    <li>      <pre>task = new sq.Task({fn: function() { log('unamed') }})
  pre>      <ul>        <li>typeof task.fn === 'function'
   li>        <li>task.name === 't0'
    li>        <li>task.level === 1
     li>        <li>task.dependencies.length === 0
      li>        <li>task.context == window
       li> 
        ul> 
         li> <li> <pre>task = new sq.Task({fn: function() { log('unamed') }, name: 'hello'})
          pre> <ul> <li>task.name === 'hello'
           li> <li>task.level === 1
            li> 
             ul> 
              li> 
               ul>

Write the code to be tested in ul li pre (CSS selector path, the same below), which is equivalent to a pre-operation. ul li tests the code and can write multiple assertions. We recommend that you use the basic data type===And!===Operator to enhance the expected judgment on the data type.

Next, we will write two helper methods for output and test:

function log(str) {  node.value += str + '\n';}function assert(expression) {  var flag;  eval('flag = ' + expression);  return typeof(flag) === 'boolean' && flag;}

logUsed to append information to a text box,assertUsed to test the input expression value. The test method is as follows (jQuery is used here ):

var sq = SmartQueue, task, total = 0, passed = 0, failed = 0;$('#J_test_cases').children().each(function(index) {  eval($('pre', this).text());  task.register();  $('li', this).each(function() {    var item = $(this);    var flag = assert(item.text());    if(flag) passed ++; else failed ++;    item.prepend((flag ? '[PASS]' : '[FAIL]') + ' ');    total++;  }).wrap('
');}).end().before('

Total: ' + total + ', passed: '+ passed +', failed: ' + failed + '

');sq.fire();

This structure can also be improved. For example, the output test description rather than the specific code can also be added with the post operation, which will not be demonstrated here. You can also view the complete test page, which contains 23 test cases and complete test implementation.

~~~~~~~~~~~~~ Gossip line ~~~~~~~~~~~~~

Well, we have realized the fun of thinking and action, and come to the end of a series of articles, but this is just the beginning. We have gone through the whole process of implementing a very small practical component and have a wonderful experience in the JavaScript world. Let's move on ~

Related Article

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.