1
头图

公众号名片
作者名片

What is "low code"? How to achieve "low code"? How to use "low code" in specific work scenarios? Tonight at 19:00, we will broadcast to you the "Practice of Low-Code Construction Platform in Baipin" on "Baipin Technology" at Station B. See you soon! Portal

foreword

Are you having a good appetite today?

Nowadays, with the continuous growth of a project business, refactoring and iteration are becoming more and more frequent. In order to ensure the stability and maintainability of the project, unit testing has gradually become a part that cannot be ignored. This article will bring an introduction to unit testing, framework selection, environment installation and writing test cases, etc. The content is relatively simple and easy to use.

what is unit testing

In computer programming, unit testing (Unit Testing), also known as module testing, is a test work for correctness testing of program modules (the smallest unit of software design). A program unit is the smallest testable part of an application. In procedural programming, a unit is a single program, function, procedure, etc.; for object-oriented programming, the smallest unit is a method, including methods in a base class (superclass), abstract class, or derived class (subclass).

The above is an explanation from Wikipedia. In a nutshell, unit testing is the examination and verification of the smallest testable unit of software. For JavaScript, it's usually tests for functions, objects, and modules.

why use it

Advantage

  • Rest assured refactoring: in the process of refactoring some business code, you don't have to worry about the side effects of the code, and the use case will automatically help in comprehensive testing;
  • Conducive to maintenance: each time new functions are iterated, and the code is updated frequently, the integrity of the test is guaranteed (because the previous test cases still exist), and the system has good maintainability, which is convenient for multi-person development;
  • Quickly familiarize yourself with the code: For newcomers to the team, unit testing is actually a better document, and each case can reflect in detail the specific functions and services contained in the code;
  • Improve code quality: If a unit test is written with very complex logic, or a function is too complex to write unit tests, it means that there is a problem with module extraction, and you can warn yourself.

Front-end mainstream testing framework

frame nameIntroduction and Advantages
JestFacebook released, simple API, quick coverage statistics, built-in commonly used testing tools, such as assertion library, is a master, easy to use
MochaBorn in 2011, the community is active, flexible and extensible, but requires additional configuration (such as assertions, you need to learn and choose tool libraries by yourself)
KarmaDeveloped by the Google team in 2012, it has a powerful feature that can monitor (Watch) file changes and execute automatically and display test results.

Assertion concept: It is to judge whether the actual execution result of the source code is consistent with the expected result, and if it is inconsistent, an exception will be thrown.

Well-known teams use Jest case

teamHundred bottlesTwitterFacebookAirbnb
Logobaiping.pngtwitterfacebookairbnb

How to choose the right framework for the front end

Project Requirements

  • Compatible with the project and the compiler
  • Fast execution of tests
  • Clear bug reports

cost

  • learning cost
  • Commissioning and maintenance costs

the old" in the treatment of technology, and in combination with its own needs, the front-end team of Baipin used Jest, combined with the 161dcf590c2532 Vue Test Utils component testing framework. More complete functions, easy to use. In addition Vue official website's evaluation of Jest is: the most comprehensive test runner.

tips: If you have written test cases for Mocha, but want to migrate to Jest framework, you can use jest-codemods for seamless migration.

Roll up your sleeves and get started

Talk is cheap, show you the code! Start building your environment right away.

There is a Vue project generated by scaffolding (if the Vue project has not been generated, you can choose to manually configure the content when creating the Vue project, and add the Jest test framework and Vue Test Utils tool library in the manual configuration).

Jest installation

Method 1:

  1. First install Jest, enter the project directory and enter the command.
npm install --save-dev jest
  1. Install Jest related dependencies.
npm install --save-dev jest babel-jest babel-core babel-preset-env regenerator-runtime

babel-jest , babel-core , regenerator-runtime , babel-preset-env installed for unit testing using ES6 syntax. import in ES6 is not supported in Jest.

  1. Add .bablerc file
{
  "presets": [
    [
      "env",
      {
        "modules": false
      }
    ]
  ],
  "env": {
    "test": {
      "presets": [
        "env"
      ]
    }
  }
}
  1. Create a jest.conf.js file for configuration
module.exports = {
  moduleFileExtensions: [
    'js',
    'json',
    'vue',
  ],
  // 告诉 Jest 处理 `*.vue` 文件
  moduleNameMapper: {
    // 支持源代码中相同的`@` => `src` 别名
    '^@/(.*)$': '<rootDir>/src/$1',
  },
  transform: {
    // 用 babel-jest 处理 js
    '^.+\\.js$': '<rootDir>/node_modules/babel-jest',
    // 用 vue-jest 处理 `*.vue` 文件 
    '.*\\.(vue)$': '<rootDir>/node_modules/vue-jest',
  }
}
  1. Add the test, script commands, and add the script of the test unit in package.json
{
  'script': {
    'test': 'jest'
  }
} 

The test command can be optimized

"test": "jest --config jest.conf.js --coverage --watch"
  • --coverage can generate coverage reports
  • --watch implements unit test monitoring, no need to run the command line when the test case is modified, and can monitor by itself
  • --config jest.conf.js is to solve the problem that the component module cannot be found when testing Vue components

Method 2:

run using the command line npx jest --init

init

  1. Install Vue Test Utils and vue-jest preprocessor.
npm install --save-dev jest @vue/test-utils
  1. To tell Jest how to process *.vue component files, we need to install and configure the vue-jest preprocessor:
npm install --save-dev vue-jest

The simplest configuration is as follows, and unit testing can be performed:

package

Note:

If you use Babel 7 or later, you need your devDependencies add in babel-bridge .

npm install --save-dev babel-core@^7.0.0-bridge.0

After the installation is complete, create the test folder and learn the official API for use in test cases.

.js in this folder and import the function add we need to test:

fun

its

Run the command npm run jest

result

So far, the basic unit test installation and use in the project has been completed.

At last

It is worth thinking that not all projects are worth introducing a test framework, after all, maintaining test cases also requires costs. It is extremely inappropriate for some content with frequent changes and low reusability. The following three situations are more suitable

  1. Projects that require long-term maintenance because they need functional stability;
  2. A relatively stable project or a relatively stable part of a project;
  3. Places that are reused many times, such as common components and library functions.

This is the end of a brief introduction to the use of front-end unit testing. I hope this article is helpful to you, and I wish you a good appetite every day!

refer to

  1. " Jest official website " https://www.jestjs.cn/docs/getting-started
  2. " Mocha official website " https://mochajs.org/
  3. " Vue Test Utils uses " https://vue-test-utils.vuejs.org/zh/
  4. " Jest + Vue Test Utils official use " https://vue-test-utils.vuejs.org/zh/guides/#%E8%B5%B7%E6%AD%A5

more exciting news, please pay attention to our public account "Hundred Bottles Technology", there are irregular benefits!


百瓶技术
127 声望18 粉丝

「百瓶」App 技术团队官方账号。