[Unit testing in js] [Quick start in 30 seconds]

What is unit testing ?
Testing is a way to verify whether our code can work as expected. In other words, it is to write some code to verify the correctness of a piece of code. The object to be tested can be style, function, process, component, etc. Unit testing is the detection and verification of the smallest testable unit in software. Unit testing can effectively improve work efficiency:
1. It can detect potential bugs
2. It can quickly feedback the output of functions
3. It can ensure the safety of code refactoring
4. It can facilitate collaborative development
How to write the simplest unit test code? Two simple unit tests are described below.

1. Write test code snippets.

Not much nonsense, just go to the code. The measured object unit such as:

let  add=(a,b)=>a+b;

   
   
    
    
  • 1

Test code:

let expect = (result) => {
      
      
    return {
      
      
        toBe: function (actual) {
      
      
            if (actual !== result) {
      
      
                throw new Error("期望值与实际值不等")
            }
        }
    }
};

   
   
    
    
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

Then you can write a method to test;

let test = function (desc, fn) {
      
      
    try {
      
      
        fn();
    } catch (e) {
      
      
        console.log(`${
        
        desc}没有通过`)
    }
}

   
   
    
    
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

Then console verification:

test('加法测试', () => {
      
      
    expect(add(1, 2)).toBe(4)
})

   
   
    
    
  • 1
  • 2
  • 3

Such a simple unit test unit test code is complete.

2. Use jest to test.

If you don't want to write unit test code, you can also use the third-party test tool jest, which is a test method in react. The following introduces the use of jest.
1. jest must be based on the node environment, first use the command line to install jest, npm i -D jestor yarn add -D jestinstall it. By npm ls jestchecking whether jest is installed successfully, if there is a jest version number, it means success.
2. Use the command line in the current workspace npm init -yto integrate the corresponding configuration items into pekage.json, as follows:.

{
      
      
  "name": "test",
  "version": "1.0.0",
  "description": "",
  "main": "text.js",
  "scripts": {
      
      
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

   
   
    
    
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  1. The preparations are done, and now you can start testing. For example, create a test file math.js in the workspace, math.js can write the code to be tested let add=(a,b)=>a+b;, and then expose the tested object to the outside module.exports={add};
let add = (a, b) => a + b;
module.exports = {
      
       add };

   
   
    
    
  • 1
  • 2
  1. In the workspace, create math.test.js as a test file. The test file needs to import the test object first, and use the test method to test. The code snippet is as follows:.
let {
      
       add } = require("./math");
test("加法测试", () => {
      
       
    expect(add(1,2)).toBe(3)
})

   
   
    
    
  • 1
  • 2
  • 3
  • 4
  1. The last and most critical step is to modify the webpack.json file. "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, change the content of test to jest, and use the command line npm run testto test the correctness of the code, so a simple unit test is completed. Here is the code snippet that passes the test:
 PASS  ./math.test.js加法测试 (2ms)

Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 1.823s
Ran all test suites.

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
summary

The above mentioned two methods of unit testing. One is to write code snippets to verify the object under test, and the other is to use a third-party jest test.

What is unit testing ?
Testing is a way to verify whether our code can work as expected. In other words, it is to write some code to verify the correctness of a piece of code. The object to be tested can be style, function, process, component, etc. Unit testing is the detection and verification of the smallest testable unit in software. Unit testing can effectively improve work efficiency:
1. It can detect potential bugs
2. It can quickly feedback the output of functions
3. It can ensure the safety of code refactoring
4. It can facilitate collaborative development
How to write the simplest unit test code? Two simple unit tests are described below.

1. Write test code snippets.

Not much nonsense, just go to the code. The measured object unit such as:

let  add=(a,b)=>a+b;

   
   
  
  
  • 1

Test code:

let expect = (result) => {
    
    
    return {
    
    
        toBe: function (actual) {
    
    
            if (actual !== result) {
    
    
                throw new Error("期望值与实际值不等")
            }
        }
    }
};

   
   
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

Then you can write a method to test;

let test = function (desc, fn) {
    
    
    try {
    
    
        fn();
    } catch (e) {
    
    
        console.log(`${
      
      desc}没有通过`)
    }
}

   
   
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

Then console verification:

test('加法测试', () => {
    
    
    expect(add(1, 2)).toBe(4)
})

   
   
  
  
  • 1
  • 2
  • 3

Such a simple unit test unit test code is complete.

2. Use jest to test.

If you don't want to write unit test code, you can also use the third-party test tool jest, which is a test method in react. The following introduces the use of jest.
1. jest must be based on the node environment, first use the command line to install jest, npm i -D jestor yarn add -D jestinstall it. By npm ls jestchecking whether jest is installed successfully, if there is a jest version number, it means success.
2. Use the command line in the current workspace npm init -yto integrate the corresponding configuration items into pekage.json, as follows:.

{
    
    
  "name": "test",
  "version": "1.0.0",
  "description": "",
  "main": "text.js",
  "scripts": {
    
    
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

   
   
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  1. The preparations are done, and now you can start testing. For example, create a test file math.js in the workspace, math.js can write the code to be tested let add=(a,b)=>a+b;, and then expose the tested object to the outside module.exports={add};
let add = (a, b) => a + b;
module.exports = {
    
     add };

   
   
  
  
  • 1
  • 2
  1. In the workspace, create math.test.js as a test file. The test file needs to import the test object first, and use the test method to test. The code snippet is as follows:.
let {
    
     add } = require("./math");
test("加法测试", () => {
    
     
    expect(add(1,2)).toBe(3)
})

   
   
  
  
  • 1
  • 2
  • 3
  • 4
  1. The last and most critical step is to modify the webpack.json file. "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, change the content of test to jest, and use the command line npm run testto test the correctness of the code, so a simple unit test is completed. Here is the code snippet that passes the test:
 PASS  ./math.test.js加法测试 (2ms)

Guess you like

Origin blog.csdn.net/m0_65450343/article/details/126275232