[] Jest unit testing tool for learning notes

Official documents address

First attach the official document address, https://jestjs.io/docs/zh-Hans/getting-started.html

 

Brief introduction

Jest is dedicated to a Javascript unit testing tool of Facebook, of course, these applications include applications React. One of its advantages is native support for React, but also very easy to support other frameworks.

 

installation

npm i jest -D (installed local)
NPM I JEST -g (into the global)

 

Interpretation of the basic configuration

  • package.json
    in package.json added configuration item "jest": {} CI
// package.json for example
...
  "jest": {
    "transform": {
      ".(ts|tsx)": "ts-jest"
    },
    "testEnvironment": "node",
    "testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$",
    "moduleFileExtensions": [
      "ts",
      "tsx",
      "js"
    ],
    "coveragePathIgnorePatterns": [
      "/node_modules/",
      "/test/"
    ],
    "coverageThreshold": {
      "global": {
        "branches": 90,
        "functions": 95,
        "lines": 95,
        "statements": 95
      }
    },
    "collectCoverageFrom": [
      "src/*.{js,ts}"
    ]
  },
...

Next, we simply talk about the role of these configuration items

  • transform

Simply put, it is a transformation configuration, such as writing here

    "transform": {
      ".(ts|tsx)": "ts-jest"
    },

Ts-jest is represented by the tool. Ts and. The TSX convert the file contents into js, because we are basically ts are also used to write test code, so you want to configure the converter

  • test environment

test environment

    "testEnvironment": "node",

That it is a class browser test environment, we can use the browser environment, some API

  • testRegex

To test the file regular expression

    "testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$",

Directory represents a test to all. Test.ts and. Spec.ts files are required to run the test

  • moduleFileExtensions

Module file name extension, when you go to introduce a module does not specify the name of expanding the time, it will in turn try to add these extensions to the proposed introduction of the module file

    "moduleFileExtensions": [
      "ts",
      "tsx",
      "js"
    ],

It represents a priority to find. TS module, followed by. The TSX and. JS

  • coverageThreshold

Test coverage threshold set, test coverage when we reach the threshold value, the test will fail

    "coverageThreshold": {
      "global": {
        "branches": 90,
        "functions": 95,
        "lines": 95,
        "statements": 95
      }
    },

Branch code represents the global coverage to more than 90%, 95% coverage of the method, the number of lines of code coverage reached 95%, 95% declare statement

  • collectCoverageFrom

Collect the specified file test coverage (even if you do not write tests for these files, it is glob patterns type)

    "collectCoverageFrom": [
      "src/*.{js,ts}"
    ]

It implies gathering src directory and all groups in the directory js and ts test coverage file

  • setupFileAfterEnv

Code files immediately after installation testing framework to perform list

    "setupFileAfterEnv": [
        "<rootDir>/test/boot.ts"
    ]

He said they would be running before every run specific test code /test/boot.ts code

It means the current root directory of the project

Other configurations you can look at the official documentation
  • jest.config.js

And add new jest.config.js CI CI module.exports = {}

 

run

  • npx jest (attached to the local premise)
  • JEST (premise mounted to the global) Review "script" in the "test" after "jest" Use npm run test

 

The basic syntax

  • Packet (the Test Group): descripe (descriptors, function)
  • Test (the Test Case): the Test (description language, function)
  • Assert (the Assert): the Expect (method of operation to be tested and return the actual result) .toBe (expected results)
// for example
Pencil.query =(name, url)=> {  //方法,返回捕获
    // ?hello=test&wonghan=handsome
    var reg = new RegExp('(?:\\?|&)' + name + '=(.*?)(?:&|$)')
    var ret = reg.exec(url) || []
    return ret[1]
}
test('query',()=>{  // testCase
    // 断言
    expect(Pencil.query('hello', '?hello=test')).toBe('test')
    expect(Pencil.query('hello', '?hello2=test')).toBe(undefined)  
    //可以写多个`ecpect()`
})
test('query2',()=>{
    expect(Pencil.query('hello/test', '?hello/test=test')).toBe('test')
}) 
    //可以写多个`test()`
describe('test query',()=>{
    test('query3',()=>{  // testCase
        // assert
        expect(Pencil.query('hello', '?hello=test')).toBe('test')
        expect(Pencil.query('hello', '?hello2=test')).toBe(undefined)
    })
})

 

It Matcher

Matchers commonly known assertion libraries, such as the above expect () toBe () is one of them, other common usage is as follows:

1. equal assertion

toBe (value): comparing numbers, strings
toEqual (value): comparison, an array
toBeNull ()
toBeUndefined ()

2. Include assertion

toHaveProperty (keyPath, value): Is there a corresponding property
toContain (item): contains a value corresponding brackets write array, a string
toMatch (regexpOrString): write regular brackets

3. logical assertions

toBeTruthy ()
toBeFalsy ()
in JavaScript, falsy six values: false, 0, '', null, undefined, and NaN. Everything else is Truthy.

toBeGreaterThan (number): greater than
toBeLessThan (number): less than

4.not

Negated, see example below uses

// for example
test('matchers',()=>{
    const a = {
        hello: 'jest',
        hi :{
            name: 'jest'
        }
    }
const b = {
    hello: 'jest',
    hi:{
        name: 'jest'
    }
}
// 以下结果均为true
expect(a).toEqual(b)
expect([1,2,3]).toEqual([1,2,3])
expect(null).toBeNull()
expect([1,2,3]).toContain(1)
expect(b).toHaveProperty('hi')
expect('123').toContain('2')
expect('123').toMatch(/^\d+$/)
expect('123').not.toContain('4')
})

 

Common stepped pit

1. Unexpected token import

Jest default only supports JS characteristics node.js version you are using supports, such as import export is not supported, so either your code compatible syntax using the system node.js write (that is, use require), or use here Babel escape it.

Solution

In Jest use in Babel is very simple, just install the babel-jest and create a new .babelrc join configuration you want on the line, Jest will automatically use babel-jest. Here we simply use babel-preset-env to the corresponding .babelrc is:

{
  "presets": ["env"]
}

Most of the time your project itself is already in use .babelrc, so this step even omitted.

Guess you like

Origin www.cnblogs.com/fe-linjin/p/11519606.html