Lainbo

Lainbo's Blog

If you’re nothing without the suit, then you shouldn't have it.
github

Introduction to Frontend Engineering 05 - Testing

What is Testing#

Wikipedia defines it as:

The process of operating a program under specified conditions to discover program errors, measure software quality, and evaluate whether it meets design requirements.

It can also be understood this way: the purpose of testing is to improve code quality and maintainability.

  1. Improve code quality: Testing is about finding bugs, identifying them, and then resolving them. With fewer bugs, the code quality naturally improves.
  2. Maintainability: The lower the cost of modifying existing code or adding new features, the higher the maintainability.

When to Write Tests#

If your program is very simple, you may not need to write tests. For example, the following program has a simple function and only a few lines of code:

function add(a, b) {
    return a + b
}

function sum(data = []) {
    let result = 0
    data.forEach(val => {
        result = add(result, val)
    })

    return result
}

console.log(sum([1,2,3,4,5,6,7,8,9,10])) // 55

If your program has hundreds of lines of code but is well encapsulated and perfectly embodies the concept of modularization, with each module having a single function and minimal code, you may also not need to write tests.

If your program has thousands of lines of code, dozens of modules, and complex interactions between them, then you need to write tests. Imagine what would happen if you modified a very complex project without tests. You would need to manually test every function related to that modification to prevent bugs from appearing. But if you have written tests, you can know the results by executing a single command, saving time and effort.

Types and Frameworks of Testing#

There are many types of testing: unit testing, integration testing, white-box testing...

There are also many testing frameworks: Vitest, Jest, Jasmine, LambdaTest...

Unit Testing#

What is unit testing? The definition given by Wikipedia is:

Unit testing (English: Unit Testing), also known as module testing, is the testing work that verifies the correctness of program modules (the smallest unit of software design).

From a frontend perspective, unit testing is testing a function, a component, or a class, targeting a smaller granularity.

How should unit tests be written?

  1. Write tests based on correctness, meaning that correct inputs should yield normal results.
  2. Write tests based on incorrectness, meaning that incorrect inputs should yield erroneous results.

To be continued...#

References#

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.