Preface:

I used to write a scribble unit test, using mocha as the testing framework and CHAI as the assertion library. After further study, I found that the cost of learning Mocha was a little high, and it ended in nothing. This time, I learned the front-end unit test again, and found it was relatively easy to learn. Because this time I chose Jest testing framework, for me this kind of unit testing small white can be up and running, and Jest is zero configuration, out of the box, but for me this kind of want to in-depth study of unit tests, look through the official documentation or well, can use advanced configuration, from in the ahead!

Main or record to Jest trample pit, this article is not in-depth article, just a simple entry!!

Because I write in TypeScript, the configuration is slightly different from JS!

All right, let’s get down to business!

introduce

Before you start, check out the official explanation of Jest.:

  1. Jest aims to work out of the box, config free, on most JavaScript projects.
  2. Make tests which keep track of large objects with ease. Snapshots live either alongside your tests, or embedded inline.

  3. Tests are parallelized by running them in their own processes to maximize performance.

  4. From it to expect – Jest has the entire toolkit in one place. Well documented, well maintained, well good.

For those of us who have forgotten English, translation software is necessary.

  • Jest is designed to be available out of the box in most JavaScript projects, free to configure.
  • Easily test to track large objects. Snapshots can be used with tests or embedded inline.
  • Tests are parallelized by running in their own process to maximize performance.
  • Jest puts the entire kit in one place. Good documentation, good maintenance.

To summarize the features of Jest:


Simple configuration, quick start, snapshot-testing, maximum test speed, good documentation. In addition, Jest has built-in assertions, asynchronous tests, custom test functions, and so on.

Other supported projects include Babel, TypeScript, Node, React, Angular, Vue, and more

For details, please go to jestjs. IO/zh-hans /.

Although it is a Chinese document, but the translation is not complete, English partners can go to the official English document to see!

(1) the installation

First, to use Jest, install the NPM package, use CMD to enter your project directory and type the following command:

cnpm install --save-dev jest typescript ts-jest @types/jestCopy the code

Js users can run the following commands:

npm install --save-dev jestCopy the code

Here I use Taobao mirror, which can speed up the download speed and installation speed. If you do not have an installation, you can enter it in the command line:

npm install -g cnpm --registry=https://registry.npm.taobao.orgCopy the code

In this way, you can use CNPM, which is taobao mirror, download speed and installation speed of a batch of fast, should be 99% of the small partners installed, it can be said that no one does not know.

2 Initialize the configuration file

Once installed, there is a jest.config.js configuration file, which is jest friendly and can be created with a single command. From the command line (CMD) and in your project directory run the following command:

npx ts-jest config:initCopy the code

To use js, run the following command:

jest --initCopy the code

To use the syntax above ES5, run Babel:

cnpm install --save-dev babel-jest @babel/core @babel/preset-envCopy the code

You can then create a babel.config.js file in the project root directory to configure the Babel compatible with your current Node version:

// babel.config.js
module.exports = {
  presets: [
    [
      '@babel/preset-env',
      {
        targets: {
          node: 'current',},},],],};Copy the code

You can refer to the official documentation for specific configuration

③ Add commands to package.json file

Next we’ll add a command to the package.json file so that we can execute the test command:

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

If you have a script property field in package.json, just add “test”: “jest”!

④ Find the Paths property in the tsconfig.json file and add the following configuration:

"paths": {
    "@App/*": ["src/baseTs/*"]}Copy the code

What does this mean? Set the path of the test directory file.

@app /* is equivalent to webpack alias, which is an individual name, don’t be scared!

⑤ Add the following configuration to the jest. Config. js file:

const { default: tsjPreset } = require('ts-jest/presets');
module.exports = {
    preset: 'ts-jest',
    rootDir: '/'transform: { ... tsjPreset.transform },testRegex: '(/test/.*\\.(test|spec))\\.[tj]sx? $',
    moduleFileExtensions: [
        "ts"."tsx"."js"."jsx"
    ],
    moduleNameWrapper: {
        '^@APP/(.*)$': '<rootDir>/src/baseTs/$1'
    },
    collectCoverageFrom: {
        "**/baseTs/upperFirst.ts"."**/baseTs/camelCase.ts".! "" **/node_modules/**".! "" **/vendor/**"}}Copy the code

These are enough, you don’t need to know what each item means, I will show it in a comment format for reference, now you just copy and paste it!

Note: I only set up two baseTs files for test coverage, upperfirst.ts and camelCase.ts!

⑥ Add a directory named test to the root directory of the project.



This is the directory where we will write the test baseTs.

⑦ Let’s start with a simple test file:

Before writing, note the following:

  • The name of the test file created in the test directory must be the same as the name of the file being tested. For example, upperfirst. ts corresponds to the test file upperfirst.test. ts (not required).
  • If you export using the ES6 module, you can import it using import in the test file, otherwise you can export it using module.exports and import it using require
  • Import files prefixed with @app /. This will cause an error if your project has an alias like @ (for SRC directory)



Test takes two arguments, the first being the result string to anticipate and the second a function (when testing asynchronous functions, there should be a done argument).

Call the Expect function, which receives a function to run, as shown in the figure above.

The result is the toBe function, which tests some basic types of data.

It is very easy to write a test code, just like mocha + chai.

Then run the following command on the cli:

npm run testCopy the code

You are ready to execute the test, which results in the following image:



Let’s test the next file:



Here I use a describe function that wraps two assertions to test.

The describe function is a suite that can be tested in groups. Other major testing frameworks include test suites.

Here are the test results:



All passed, is not very happy!

To explain the coverage (that is, what each cell in the table represents) :

  • % STMTS is statement coverage: whether each statement is executedCopy the code
  • % Branch Coverage: Whether all conditional statements are executedCopy the code
  • % Funcs function coverage (functionCoverage: Whether all the functions are calledCopy the code
  • % Lines Line coverage: the number of Lines of code not executedCopy the code

Except for half of the conditional statements, the rest are above 90%, indicating that the code quality is ok.

Of course, such a pass rate can be achieved because the code is relatively simple, and the unit test can let us know how the quality of the code is, and then we can reconstruct the code with high quality. Take one of my two files as an example (the modified code) :



Although this simple hump function is a bit long after modification, it basically conforms to one of the more important principles of object orientation, that is, a single responsibility, a function only does one thing! It also basically conforms to the open and closed principle, because the main function is pieced together with small functions, so if we want to transform the main function in the future, we only need to transform it in the pieced function, the main function does not need to move.

For example, if I want to change the regex judgment, I just need to change it in the regex function.

So unit testing is really important. Many of you may not have written it, but if you write it, it will improve your existing code and make it easier to refactor. As a result, it will improve the quality and maintenance of your code.

Finally, let’s have a look at the basic configuration of Jest. I spent a whole afternoon sifting through it. For those who are just getting started, you can go to the official documentation for the advanced configuration.

Here I have carried on the explanation with the annotation (personal understanding)!!

The following is the jest.config.js configuration:

You can set the notes as detailed as possible according to your own project and directory, which is convenient for your friends to refer to. Since I am in the pit of unit testing again, I still need to continue to work hard, I hope you can point out the mistakes, if there are some tips or articles about Jest unit testing, please also attach links and suggestions in the comments

The following link is attached:

Jest中文 网 址 address: jestjs. IO/zh-hans /

Ts-jest document address: kulshekhar.github. IO /ts-jest/

Jest configuration file address: jestjs. IO /docs/ zh-han…

The above configuration is to refer to the second, third address!!