Front End unit Test summary and test tool introduction

Source: Internet
Author: User

1. Why unit testing is required
    • Correctness: The test can verify the correctness of the code, before the launch of the Heart
    • Automation: Of course, manual can also be tested, through the console can print out internal information, but this is a one-time thing, the next test will need to start over, efficiency can not be guaranteed. By writing test cases, you can write and run multiple times.
    • Explanatory: test cases are used to test the importance of interfaces and modules, so the use of these APIs is covered in test cases. If other developers want to use these APIs, reading test cases is a good way, sometimes clearer than document descriptions
    • Driver development, Guidance Design: Code is tested on the premise that the code itself testability, then to ensure the testability of the code, you need to pay attention to the design of the API in development, TDD will test forward is to play such a role
    • Guarantee Reconstruction: The Internet industry product iteration speed quickly, after iteration inevitably exists the process of code reconstruction, how can guarantee the quality of the reconstructed code? With test cases backed up, you can refactor boldly
2. Front-end related unit testing technology

2.1 Test Framework

At present, the front-end testing framework, such as Qunit, Jasmine, mocha, jest, intern and other frameworks, these frameworks have characteristics, a simple description, interested can be specific research:

    • Qunit: The framework was first created for the unit test of jquery, and was later independent from the jquery itself, but it was still out of the shadow of jquery.
    • Jasmine:behavior-drive Development (BDD)-style test framework, which is popular in the industry, features a comprehensive, self-asssert, mock function
    • The works of the Mocha:node community, the great God TJ, can be used on the node and the browser side, with the flexibility to choose your favorite assertion library and select the report of the test results
    • Intern: Look at the official introduction The test framework is extremely versatile and seems to encompass all of the industry's testing-related features

2.2 Assertion Library

    • Chai: Should be the current set of popular assertion libraries, support TDD (assert), BDD (expect, should) two styles of assertion library
      var chai = require (' Chai '); var assert = Chai.assert; Typef assert = = = ' object ' Chai.should (); To expand the Obejct.prototype
    • Another open source contribution from Should.js:TJ
    • Another assertion library of the Expect.js:BDD style, based on Should.js, is the mini version of the BDD library
    • ASSERT (node comes with core module): Assertion module that can be used in node

2.3 Mock Library

First of all, why do you need a mock?: The unit that needs to be tested depends on the external modules, and these dependent modules have some characteristics, such as uncontrollable, high cost, operational risk, etc., cannot directly use dependent modules, in which case it is necessary to mock, that is, to forge dependent modules. For example, when using XMLHttpRequest, it is necessary to simulate the case of HTTP statuscode of 404, which is actually very difficult to happen, and it is necessary to implement the test by mock.

    • Sinon.js: Currently the most used mock library, divided into spies, stub, fake XMLHttpRequest, fake server, fake time, according to different scenarios to choose.

2.4 Test Runner

    • Karma: Set up the framework, environment, source files, test files, etc. required for testing, and then you can easily perform the tests when you have finished configuring them.
3. Principle of Unit Test technology implementation
    1. Test framework: To determine whether there is an exception inside, the console out of the corresponding text message
    2. Assertion Library: When the actual value is different from the expect value, an exception is thrown for the external test framework to detect, which is why some test frameworks are free to choose the reason for the assertion library, and the external test framework can work as long as exceptions can be thrown.
    3. Mock function: Create a new function, replace the original function with this function, and add some additional attributes on the new function, such as called, calledwitharguments, etc.
      function describe (text, fn) {    try {        fn.apply (...)    } catch (e) {        assert (text)    }} function fn () {
           
            while (...) {        Beforeeach ();           It (text, function () {            assert ();        });         Aftereach ();    }} function it (text, fn) {    ...    fn (text)    ...} function assert (expect, actual) {    if (expect not equla actual) {        throw new Error (text); 
            }}FUNCTION fn () {    ...} function Spy (CB) {    
            proxy = function () {        ...    }    proxy.called = false;    Proxy.returnvalue = ' ... ';    ...    return proxy;}  var proxy = Spy (FN); Get a mock function
           
4. How to write unit test cases

4.1 Principles

    • When testing code, consider only testing, regardless of internal implementation
    • Data as much as possible to simulate reality, the closer to reality the better
    • Take full account of data boundary conditions
    • Focused, complex, core code, key testing
    • Use AOP (Beforeeach, Aftereach) to reduce the number of test codes and avoid useless functions
    • Combination of testing and functional development facilitates design and code refactoring

4.2 TDD

To put it simply, it is to write the test first, then write the function to implement. The goal of TDD is to use test cases to guide the actual development of functionality, so that developers can first look at the requirements from a global perspective. Specific definitions can be viewed Wiki;

In individual terms, TDD is not a technology, but a guideline for development. In the current development environment of the Internet, it is very difficult to develop TDD, one is because more time is needed to write unit test cases, the other is to understand the business requirements very well, and the third is to require developers to have strong code design ability. But when we write components, tools, libraries, TDD can be used very well.

4.3 BDD

Behavioral-driven development requires more people to participate in software development, encouraging developers, QA, and related business people to work together. BDD is driven by business value and understands the application through a user interface (such as a GUI). See wiki.

Front End unit Test summary and test tool introduction

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.