Front-end testing: unit testing

why test

Do you have the following troubles:

  • After you work overtime to complete a function, submit it to the testing department and immediately return several bugs

  • After you have modified the bug and checked it several times to make sure it is correct, submit it to the testing department and return a few bugs

    ……

For the above situation, have you ever had any doubts, why the inspection is all right or there is a bug? All of these are due to lack of testing.

You may ask, did it, and checked it several times. Indeed, you have tested, but you have not completed the closed loop of testing. You may complete some parts of the test and not others. Since you said I didn't complete the test, what is the test and how to conduct the test?

What is a test?

For the front end, testing is mainly to test HTML, CSS, and JavaScript to ensure the normal operation of the code.

Common tests include unit tests, integration tests, and end-to-end (e2e) tests.

  • Unit testing: testing the smallest testable unit in the program. We can compare it to the testing of a car. Before the car is assembled, the parts need to be tested. In this case, it is consistent with the unit test. Only when the parts are normal can the next step of assembly be carried out
  • Integration testing: Testing an entirety of executable units. Similar to the test of a car, it is equivalent to testing the engine as a whole by assembling the parts required for the engine before testing the engine.
  • End-to-end testing: testing from server to client. This kind of test is to test the entire system composed of the server and the client, and it is a test that can execute a complete process.

Now that we know that there are these types of tests, let's talk about how these tests should be implemented.

how to test

The testing methods can be divided into manual testing and automatic testing.

Manual testing: It is to let the personnel of the testing department operate according to the business process. When a problem occurs in a certain step or steps, it means that there is a problem with this part of the code. This test method has obvious shortcomings:

  1. It can only test the part that the tester can see, and cannot test the part that the tester cannot see. For example, some internal utility functions, logic codes, etc., these are likely to have problems.

Automated testing: Use the written code to test the code. This kind of test can make up for the lack of manual testing. Its granularity is at the code level and can accurately identify errors in a certain method.

Therefore, in the actual development process, we can use manual testing + automatic testing to test, and strive to cover 100% of the testing goals. Leaving aside manual testing, let's talk about automatic testing to achieve unit testing, integration testing, and e2e testing. This blog first talks about unit testing.

unit test

There are many libraries and frameworks that implement unit testing. This article uses Jest as an example to explain.

Why choose jest?

advantage:

  • relatively new
  • good foundation
  • Fast speed: support single module testing, reduce test code
  • Simple API: easy to use
  • Good isolation: files are independent of each other
  • IDE integration: vscode plugin
  • Multi-Project Operations: Increased Efficiency
  • coverage: export test coverage

It is relatively simple to use jest for unit testing, because Jest provides many convenient APIs for developers to use.

Install

npm install jest -D

Generate default configuration

npx jest --init

listen test file

After executing the following command, jest will monitor the test file and automatically execute the test when the file changes

npx jest --watchAll

jest uses glob patterns when matching test files, and jest test files have the suffix .test.js.

grammar

Create test groups

describe('description',()=>{
    
    
    
});

We use the describe() method to create test groups in which there can be multiple test cases. The first parameter is the description of the test group, and the second parameter is the callback function, in which the test case is created.

Test cases are created using the est() method:

test('description',()=>{
    
    });

The first parameter of the test() method is the description of the test case, and the second parameter is the callback function, where the assertion and matching are performed.

We can create assertions using the expect() method, using the match method to match the value we expect:

expect(true).toBe(true);

matching method

Matching methods for various data types are provided in Jest

boolean

toBeFalsy() is used to match false values

expect(false).toBeFalsy()

The toBeTruthy() method matches the truth value

expect(true).toBeTruthy();
object

toEqual() matches the object, this method performs deep matching, that is, each key-value pair in the matching object

array

The toContain() method matches elements in the array

expect(6).toContain([6,7,8]);
string

The toMatch() method matches elements in a string.

expect('hello').toMatch('hello world');
undefined

The toBeUndefined() method matches the value of undefined

let a;
expect(a).toBeUndefined();

Correspondingly, toBeDefined() is used to match defined values

let a = 1;
expect(a).toBeDefined();

Test asynchronous code

Jest provides a method for testing asynchronous code, which is used to test asynchronous code. The methods of testing asynchronous code include callback function test, promise test, async&await test

callback function test

The callback function test will receive a done parameter in the callback function of test. This parameter is a function that executes done() after the asynchronous code is executed.
Use fetch to send a request in fetchData, execute the callback function when the request is successful, and test the returned data in the callback function.

test('回调函数',(done)=>{
    
    
	fetchData((responseData)=>{
    
    
    	expect(responseData).toEqual({
    
    name:'hello'});
    	done();
  });
})
Test with promises

To test code using promise, you need to return promise in the callback function of the test() method.

test('异步代码promise方法测试',()=>{
    
    
  return fetchData().then(res => {
    
    
    expect(res).toEqual({
    
    name:'hello'});  
  });
});
async... await tests asynchronous code
test('async……await测试异步代码',async ()=>{
    
    
  await expect(fetchData()).resolves.toMatchObject({
    
    
    data:{
    
    
      success:true
    }
  });
});

Jest's hook function

Jest's hook function is a function that is executed at different stages during the execution of the test case. There are four in total: beforeAll, beforeEach, afterEach, and afterAll.

  • beforeAll: execute before all test cases
  • beforeEach: executed before each test case is executed
  • afterEach: Executed after each test case is executed
  • afterAll: execute after all test cases

These hook functions also have scope, and they obey the following rules:

  • The hook function can act on the subset in the parent group
  • The scope of hook functions at the same level does not interfere with each other
  • Execute the external hook function first, and then execute the internal hook function

Guess you like

Origin blog.csdn.net/qq_40850839/article/details/130955064