Currently, testing is a very important part of developing large-scale applications, but most front-end developers lack knowledge about testing. You don’t realize the importance of front end automation because you may never have a chance to write a project with a short development cycle.

Tell us why front-end automation testing is so important!

Let’s start with common front-end problems:

  • It is difficult to change the function of one module quickly because other modules are affectedQuickly locate the bug
  • Multiplayer development code is increasingly difficult to maintain
  • It is not easy to iterate and the code cannot be refactored
  • Poor code quality

After adding automated tests:

  • After we write tests for core functions, we can guarantee the projectreliability
  • Forcing developers to write code that’s easier to test,Improve code quality
  • Written tests serve as documentation,Convenient maintenance

1. Test Introduction

1.1 Black box test and white box test

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

1.2 Test Classification

Unit Testing

Unit testing refers to testing the smallest testable unit of a program, such as testing a function, a module, a component…

Integration Testing

The encapsulation of high-level functions or classes exposed by composite integration of tested unit test functions

E2E Testing opens the application to simulate input and check that the functionality and interface are correct

1.3 TDD and BDD

TDD is Test-Driven Development

TDD works by writing unit test case code before developing functional code

BDD is behavior-Driven Development

System business experts, developers, and testers work together to analyze the requirements of the software and then write stories about those requirements. It’s the developer’s job to fill in the blanks and make sure the application works the way the user wants it to.

Summary:

TDD is about writing tests first and developing them later (usually unit tests, white box tests); BDD, on the other hand, is based on the user’s behavior and then writes test cases based on the user’s behavior (generally integration tests, black box tests).

1.4 Testing Framework

  • Karma: Karma provides the ability to test across browsers for front-end automation testing, executing test cases in a browser
  • Mocha: Front-end automation testing framework that needs to work with other libraries like CHAI, Sinon…
  • Jest: Jest is a Facebook testing framework that integrates Mocha, Chai, Jsdom, Sinon, and more.
  • .

Facebook is pushing Jest, don’t you want to learn? Jest also has a few drawbacks: it doesn’t run directly in a browser like Karma. It uses JsDOM and has the advantage of simple, zero configuration! Next we’ll talk about front-end automation testing via Jest.

2. Core application of Jest

Before we talk about Jest testing, how did we test it before

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
Copy the code

Every time we write a feature, we need to test it manually. After the test, we may comment out the test code, which can cause a series of problems. All the test code is mixed with the source code because it will pollute the source code. If you delete it, the next test will need to be rewritten.

So the testing framework solves that problem for us

2.1 Grouping and use cases

Jest is based on modules. We need to package the code into modules and export the two methods parser and Stringify respectively by using export.

Install the jest

npm init -y # Initialize pacakge.json
npm i jest  
Copy the code

We create qs.test.js to write test cases, which you can think of as a test function (the suffix ends with.test.js, so that jEST tests call this file by default).

import {parser,stringify} from './qs';

it('Test parser to see if it parses properly', () = > {// expect the result to be the same as {name:' webyouXuan '}
    expect(parser(`name=webyouxuan`)).toEqual({name:'webyouxuan'});
})
Copy the code

By default, jest has a built-in assertion function, which means to determine if this is the case. I’m sure you didn’t eat today. If you did, this assertion fails and the test fails.

Execute commands by configuring scripts

"scripts": {
    "test": "jest"
}
Copy the code

NPM run test: NPM run test is not supported in node by default. You can also use the CommonJS specification to export methods. Most development uses es6 modules, so you can install it.

# core is Babel's core package preset-env converts ES6 to ES5
npm i @babel/core @babel/preset-env --save-dev
Copy the code

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

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

Babel-jest is integrated into Jest by default, which is escaped by default at runtime. Babelrc can be directly converted from ES6 to ES5 syntax. NPM run test

Continue writing the second use case

import {parser,stringify} from './qs';
describe('Test QS Library',()=>{
    it('Test parser to see if it parses properly',()=>{
        expect(parser(`name=webyouxuan`)).toEqual({name:'webyouxuan'});
    });
    
    it('Test if stringify is used properly',()=>{
        expect(stringify({name:'webyouxuan'})).toEqual(`name=webyouxuan`)})});Copy the code

The function of Describe is to group use cases so that it is better to classify use cases. In fact, this is what we call unit testing, testing specific functions and functions.

2.2 Matchers

When we wrote our first test case, we were using toEqual which is essentially a matcher, so what are the matchers that we use in jest? Because there are so many matchers, I will talk about some common ones!

For ease of understanding, I have divided matchers into three categories: equal, unequal, and inclusive.

it('Determine equality',()=>{
    expect(1+1).toBe(2); // equivalent to js ===
    expect({name:'webyouxuan'}).toEqual({name:'webyouxuan'}); // Compare the contents to be equal
    expect(true).toBeTruthy(); // toBe(true)
    expect(false).toBeFalsy();
});

it('Judge unequal relation',()=>{
    expect(1+1).not.toBe(3); / / not take back
    expect(1+1).toBeLessThan(5); // js is less than
    expect(1+1).toBeGreaterThan(1); // js is greater than
});

it('Check for inclusion',()=>{
    expect('hello world').toContain('hello'); // Whether to include
    expect('hello world').toMatch(/hello/); / / regular
});
Copy the code

2.3 Test operation node method

Say a long time, let’s write a function test by ourselves!

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

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

import { removeNode } from './dom'
it('Test node deletion', () = > {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()
})
Copy the code

This is what we call jsDOM, manipulating DOM elements in node

2.4 Common Jest Commands

We want to automatically re-execute the tests after each test change, modifying the execution command:

"scripts": {
    "test": "jest --watchAll"
}
Copy the code

Re-execute the NPM run test, at which point the user changes will be monitored

We are prompted to press W to display more information

I’ve listed the meanings of each command here, so you can try them out for yourself if you need to

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