At present, testing is a very important part of developing large applications, but most of the front-end developers have little knowledge about testing. You can’t appreciate the importance of front-end automated testing because the project cycle is too short to write at all.

Talk about why front-end automated testing is so important!

Let’s take a look at some common front-end problems:

  • When you modify the function of a module, other modules will also be affected, making it difficult to locate bugs quickly
  • Multiple development code is becoming harder and harder to maintain
  • Inconvenient iteration, code cannot be refactored
  • Poor code quality

After adding automated tests:

  • When we write tests for the core functionality, we ensure the reliability of the project
  • Improve code quality by forcing developers to write code that is easier to test
  • Written tests have the function of documentation, easy maintenance

1. Test introduction

1.1 Black box testing and white box testing

  • Black-box testing, also known as functional testing, requires the tester to look at the program as a whole, regardless of its internal structure and characteristics, but to verify that the program works as expected
  • White box testing is based on the code itself, generally refers to the test of the logical structure of the code.

1.2 Test Classification

Unit Testing

Unit tests are tests performed on the smallest testable unit of a program, such as testing a function, a module, a component…

Integration Testing

The combination of tested unit test functions and the encapsulation of exposed high-level functions or classes that are tested

E2E Testing opens the application to simulate input and checks that the functionality and interface is correct

1.3 TDD and BDD

TDD is Test-Driven Development

The principle of TDD is to write unit test case code before developing functional code

BDD is Behavior-Driven Development.

Systems business experts, developers, and testers work together to analyze software requirements and then write stories about those requirements. It is the developer’s responsibility to fill in the content of these stories and ensure that the application implementation is consistent with the user’s needs.

Summary:

TDD is writing tests before developing them (usually unit tests, white box tests); BDD, on the other hand, is based on user behavior, and then based on user behavior, write test cases (usually integration tests, black box tests).

1.4 Test framework

  • Karma: Karma provides cross-browser testing capabilities for front-end automation, executing test cases in the browser
  • Mocha: Front-end automated testing framework that needs to be used with other libraries, such as Chai, Sinon…
  • JEST: JEST is a testing framework from Facebook that integrates Mocha, Chai, JSDOM, Sinon and other features.
  • .

Facebook is tweeting JEST, don’t you want to learn? Jest also has a few disadvantages that it can’t run directly in the browser like Karma. It uses JSDOM and has the advantage of simple, 0 configuration! We’ll talk about front-end automated testing through JEST later.

2. Core applications of JEST

Before we talk about the JEST test, how did we test it in the past

const parser = (str) =>{
    const obj = {};
    str.replace(/([^&=]*)=([^&=]*)/g,function(){
        obj[arguments[1]] = arguments[2];
    });
    return obj;
}
const stringify = (obj) =>{
    const arr = [];
    for(let key in obj){
        arr.push(`${key}=${obj[key]}`);
    }
    return arr.join('&');
}
// console.log(parser('name=webyouxuan')); // {name:'webyouxuan'}
// console.log(stringify({name:'webyouxuan'})) // name=webyouxuan

Every time we write a function, we need to manually test whether the function is normal, and after testing, we may comment the test code, which will cause a series of problems. Because of the contamination of the source code, all the test code is mixed with the source code. If it is removed, it will need to be rewritten for the next test.

So the testing framework helps us solve these problems

2.1 Grouping and use cases

JEST is modules-based, so we need to wrap the code in modules, exporting Parser and Stringify using export methods, respectively.

Install the jest

NPM init -y # Initiate pacakge.json NPM I jest

Js, which you can think of as a test function. (The suffix should end with.test.js, so that this file will be called by default when JEST tests.)

import {parser,stringify} from './qs'; It (' Parser parses the result correctly ',()=>{// Expect assertion, Expect (parser(' name= 'webyouxuan')).toequal ({name:'webyouxuan'}); })

JEST has an assertion function by default, the assertion means to judge whether this is the case. I conclude that you didn’t eat today ~, but you did, which means that this assertion fails, and the test cannot pass.

Configure scripts to execute commands

"scripts": {
    "test": "jest"
}

Npm run test is not supported by default in the Node environment, which requires Babel escape. You can also export methods using the CommonJS specification directly, since most current development uses the ES6 module, so just install it.

# core is Babel's core package preset-env which converts ES6 to ES5 NPM i@babel/core@babel /preset-env --save-dev

And you need to configure the.babelrc file to tell Babel what to escape with

{
    "presets":[
        [
            "@babel/preset-env",{
                "targets": {"node":"current"}
            }
        ]
    ]
}

By default, babel-jest is integrated into JEST, and by default, the runtime calls.babelrc to escape it, which translates ES6 directly into ES5 syntax. NPM run test

Go ahead and write the second use case

import {parser,stringify} from './qs'; Expect (parser(' name=webyouxuan ')).toequal ({name:'webyouxuan'}); }); Expect (stringify({name:'webyouxuan'})).toEqual(' name= 'webyouxuan')})});

describeIn fact, this is what we call unit testing, which tests a specific function or function.

2.2 Matchers

When we wrote our first test case, we used toEqual all the time which is really just a matcher, so let’s see what are the matchers that are commonly used in JEST? There are too many matchers, so I’ll talk about some commonly used ones!

For ease of understanding, I’ve divided matchers into three categories: equality, inequality, and inclusion.

Expect (1+1).tobe (2); expect(1+1).tobe (2); Expect ({name:'webyouxuan'}).toequal ({name:'webyouxuan'}); Expect (true).tobetruthy (); // True/false can also be used toBe(true) expect(false).tobefalsy (); }); Expect (1+1).not. Tobe (3); expect(1+1).not. // not inverse expect(1+1).tobelessthan (5); // Expect (1+1).tobeGreaterThan (1); // > >}); It (' judgment whether to include '() = > {expect (" hello world "). ToContain (" hello "); // Include Expect ('hello world').tomatch (/hello/); / / regular});

2.3 Test operation node method

Say along while, we come to write a function test by ourselves!

export const removeNode = (node) => {
    node.parentNode.removeChild(node)
};

The core is to test whether a node passed in can be removed from the DOM

Import {removeNode} from './dom' it(' test delete node ',()=>{document.body.innerHTML = '<div><button' data-btn="btn"></button</div>` let btn = document.querySelector('[data-btn="btn"]') expect(btn).not.toBeNull() removeNode(btn); btn = document.querySelector('[data-btn="btn"]'); expect(btn).toBeNull() })

This is what we call JSDOM, which manipulates DOM elements in Node

2.4 JEST common commands

We want the test to be automatically reexecuted after each change, modifying the execution command:

"scripts": {
    "test": "jest --watchAll"
}

Re-execute NPM run test, and the user’s changes will be monitored

It prompts us to press W to display more information

I have listed the meaning of each command here, so you can try it out yourself if you need to

Want to know how to test asynchronous logic, mock interface data, and use JEST in depth? Stay tuned for the next post!