• Mainstream testing frameworks include Jasmine, MOCHA, Jest, etc.
  • Compared with other testing frameworks, Jest has the advantages of good foundation, fast speed, simple API, good isolation, multi-project running (such as React write foreground, Node write background can be parallel), and coverage
NPM install [email protected] -d ## Since the test framework is used in the development environment, adding -d will only use the package in the development environment, not in the production environment. {"name": "jest_test", "version": "1.0.0", "description": "", "main": "Index. Js", "scripts" : {" test ":" jest "}, "author" : ""," license ":" ISC ", "devDependencies" : {" jest ":" ^ 24.8.0 "}}Copy the code

Unit testing and integration testing

  • Unit testing refers to the detection and verification of the smallest testable units in the software. The front-end unit testing refers to the testing of a module. That is to say, when the front-end test, the test must be a module.
  • Integration tests are assembly tests. On the basis of unit test, all modules are assembled into subsystems for integration test. (That is, test all modules together)

Initial configuration of Jest

npx jest --init

  • After entering the command, options will appear, mainly information about the running environment and whether to generate test coverage files. In the root directory, there is a jest.config.js file, which is full of jest configuration items.

coverageDirectory

This configuration item in the jest.config.js file is used to generate code coverage files

  • Typing NPX jest — Coverage in the console will generate a coverage folder containing the test report

Jest’s matcher

  • Jest allows you to test for consistency of types similar to data
ToBe matches strictly like === toEqual matches strictly like == toBeNull matches Null toBeUndefined matches undefined toBeDefined matches as long as it is defined ToBeTruthy matches true toBeFalsy matches false toBeGreaterThanOrEqual is greater than or equal to toBeCloseTo can check floating point numbers toMatch matches string toContain matches array toThrow Check if there is an exception, there is no exception through not. ToThrow checkCopy the code

Jest automatic testing

  • Just add the –watchAll NPM run test command to the value of the scripts tag in the package.json file and modify the test file to automatically test

Jest support ES6

{
    "presets": [["@babel/preset-env", {"targets": {"node":"current"}}]]}Copy the code

Asynchronous code test methods

  • Callback function mode
    • Use the AXIos library to do network requests and install commandsCNPM install [email protected] - save
import { fetchData } from './fetchData'

test('Network Request'.(done) = > {
    fetchData(data= >{
        expect(data).toEqual({
            "msg":"hello!!"}) done()})}) ## The network request must be added to the done method to ensure that our callback has completedCopy the code

Jest’s assertion

  • It is easy to catch the request error by using catch directly in test 404
test("To test the 404".() = >{
	return fetchThreeData().catch((e) = >{
    	expect(e.toString().indexOf('404') > -1).toBe(true)})})Copy the code
  • This does catch thrown errors and test them. But if the page does not throw an error, jEST detection does not report an error.
  • Because the request didn’t throw an error, I called the catch method instead. Don’t use this method because there are no exceptions. Jest passes this test by default.

Cases like this require jEST assertions. To use it, expect must be performed once

test("To test the 404".() = >{
	expect.assertions(1) / / Jest assertion
	return fetchThreeData().catch((e) = >{
    	expect(e.toString().indexOf('404') > -1).toBe(true)})})// Now the test case will not pass the test. Because our test is a test request error. Code like this is more robust in unexpected situations
Copy the code

Asynchronous code

  • Using async… Await the form of
    • The async function returns a Promise object, which will be returned as soon as an await is encountered when the function executes. When the triggered asynchronous operation is complete, the subsequent statements in the function body are executed.
    • A promise object is required after the await keyword, and if not, a call to resolve is required to transform it

test('test'.async() = > {await expect(fetchFourData()).resolves.toMatchObject({
    	// Use convergenceBetween current objects and promise objects
        // toMatchObject Matches all attributes of the object
    	data: {success:true}})})Copy the code

Jest’s hook function

  • If you have experience developing VUE or React, you don’t need much introduction to hook functions. You wouldn’t normally use automated testing without that development experience. Ha, ha, ha

  • Jest has four hooks

    • BeforeAll () all test cases are called before

    • AfterAll () is called afterAll test cases

    • BeforeEach () is called beforeEach test case fires (fires several times if there are several)

    • AfterEach () Each test case test completion call (several times triggered)

Jest grouping

  • Jest provides a grouping method describe() that takes two parameters
    • String ———— “Name”
    • The callback function ———— places the test method
describe('Chrysanthemum Warp and Weft'.() = >{
   test(' 按脚 '.() = > {
       baojian.gongzhu(1)
       baojian.AnJiao()
       console.log( baojian.fuwu );
       expect( baojian.fuwu ).toEqual( 'Ju Qianwei will touch your feet' )
   })
   test('court'.() = > {
       baojian.gongzhu(1)
       baojian.gtzl()
       console.log( baojian.fuwu );
       expect( baojian.fuwu ).toEqual( 'Ju Qianwei comes to court to tease')})})Copy the code

Scope of the hook function

  • Hook functions can scope subsets in parent groups, similar to inheritance
  • The hook functions are grouped in the same scope without interfering with each other
  • The external hook function is executed before the internal hook function is executed
/** * Test case grouping */
describe('Chrysanthemum Warp and Weft'.() = >{
   beforeAll(() = >{
       console.log('Ju Jing Wei group ___ first implemented');
   })
   test(' 按脚 '.() = > {
       baojian.gongzhu(1)
       baojian.AnJiao()
       console.log( baojian.fuwu );
       expect( baojian.fuwu ).toEqual( 'Ju Qianwei will touch your feet' )
   })
   test('court'.() = > {
       baojian.gongzhu(1)
       baojian.gtzl()
       console.log( baojian.fuwu );
       expect( baojian.fuwu ).toEqual( 'Ju Qianwei comes to court to tease')})})/** * Test case grouping */

describe('Three Tangerines'.() = >{
   afterEach(() = >{
       console.log('All tests will be executed after completion of the triple Orange Mosaic test method');
   })
   test('massage'.() = > {
       baojian.gongzhu(2)
       baojian.AnMo()
       console.log( baojian.fuwu );
       expect( baojian.fuwu ).toEqual( "Three orange blossoms to touch." )
   })
   test('desktop'.() = > {
       baojian.gongzhu(2)
       baojian.taishi()
       console.log( baojian.fuwu );
       expect( baojian.fuwu ).toEqual( 'Three orange flowers for desktop health care')})})/ * the console. The log fetchData/newBaoJian. Test. Js: 31 chrysanthemum jinwei group ___ first perform the console. The log fetchData/newBaoJian test. Js: 36 JuQianWei to foot The console. The log fetchData/newBaoJian. Test. Js: 42 JuQianWei to court Lord snatched the console. The log fetchData/newBaoJian test. Js: 58 three orange decorated to according to touch the console. The log FetchData/newBaoJian. Test. Js: 53 three orange decorated group after completion of test methods, Will perform the console. The log fetchData/newBaoJian. Test. Js: 64 three orange decorated to taiwan-style console log fetchData/newBaoJian test. Js: 53 three orange decorated group after completion of test methods, All execute */
Copy the code

Jest knowledge new add ———— only

  • Using this method only executes the current test case
describe('Chrysanthemum Warp and Weft'.() = >{
   beforeAll(() = >{  
       console.log('Ju Jing Wei group ___ first implemented');
   }) / / execution
   
   test.only(' 按脚 '.() = > { 
       baojian.gongzhu(1)
       baojian.AnJiao()
       console.log( baojian.fuwu );
       expect( baojian.fuwu ).toEqual( 'Ju Qianwei will touch your feet')})/ / execution
   
   test('court'.() = > { 
       baojian.gongzhu(1)
       baojian.gtzl()
       console.log( baojian.fuwu );
       expect( baojian.fuwu ).toEqual( 'Ju Qianwei comes to court to tease')})/ / does not perform
})
Copy the code