current position:Home>[jest] a pleasant testing framework (I)

[jest] a pleasant testing framework (I)

2021-08-27 09:39:53 GavinUI

Use jest Why

With the development of the front end ,web Our interactions are getting more and more complex , Automated testing is very necessary to integrate into the development process , At present, there are facebook Developed Jest This set of tools . He can create test cases , Perform the test , It has its own drivers and mock, And it is also very convenient to use , just as jest The official website of jest,Jest is a delightful JavaScript Testing Framework with a focus on simplicity.

Verify that the parameters are correct

jest It provides a variety of matchers, which can match different data types , such as :array,string,object wait , And their matchers are toContain ,toMatch,toEqual. meanwhile , jest It also supports mismatch verification , That is, reverse verification . Here are some different matchers .

Simple type verification ;

Use tobe() The matcher does simple type verification , Check whether the result is correct .

// index.js
const sum = (a, b) => {
    return a + b;
}

// index.test.js
test('adds 1 + 2 to equal 3', ()=>{
    expect(sum(1,2)).toBe(3)
});
 Copy code 

Verification of arrays or objects

// index.js
const objectTest = () => {
    const data = {name: 'jest'};
    data['age'] = 20;
    return data;
}  

// index.test.js
test('object test', ()=>{
    const obj = sum.objectTest();
    expect(obj).toEqual({name: "jest",age: 20})
});
 Copy code 

toEqual Recursively check objects or arrays .

Judge whether the data is empty

The official document names this kind of verification as Truthiness , That is, effectiveness . Here is my own understanding , I usually call this situation “ empty ”, Not only can we judge null You can also judge undefine And so on .

// index.js
const nullTest = () =>{
    return null;
};

// index.test.js
test('null test', ()=>{
    const params = sum.nullTest();
    expect(params).toBeNull()
});
 Copy code 

Conditional judgment

image number This type , He can also judge whether it is greater than a certain value .

// index.js
const sum = (a, b) => {
    return a + b;
}

// index.test.js
test('adds 1 + 2 to equal 3', ()=>{
    expect(sum(1,2)).toBeGreaterThan(2)
});
 Copy code 

Determine character type

Character types are verified by adding matching .

// index.js
const textTest = () =>{
    return 'there is no I in team';
};

// index.test.js
test('there is no I in team', () => {
    expect(sum.textTest()).toMatch(/I/);
});
 Copy code 

Verify whether the parameters are correct in the case of asynchrony

callback Function verification

Use jest When doing callback operation test, you should pay attention to , The return of the function . Like the following code :

test('success', () => {
  function callback(data) {
    expect(data).toBe('success');
  }
  fetchData(callback);
});
 Copy code 

This situation is specially marked on the official website , In this way, you can't get his asynchronous state , After his synchronization code is executed , To get asynchronous data , And here he's done ,test It stopped. .

The wording that should be changed to is :

test('test ajax', done => {
    function callback(data) {
        try {
            expect(data).toBe('fight');
            done();
        } catch (error) {
            done(error);
        }
    }
    sum.fetchData(callback);
});  
 Copy code 

When done If this parameter function has not been executed , This test The use case will report an error . stay ecpect After execution fails , Not execute done(). meanwhile , He will trigger catch Output error journal .

promises Asynchronous verification

Use promises Then there will be a simpler way to verify , Just return one promises , Listen to this again promises Of resolve state . The code is as follows :

// index.js
const promiseFetchData = async () =>{
    return new Promise((resolve,reject)=>{
        resolve('fight');
    })
}
// index.test.js
test('test ajax', () => {
    return promiseFetchData().then((data)=>{
        expect(data).toBe('fight')
    });
});  
 Copy code 

resolve Pass the return value , Give it back expect Receive verification .

async / await

Use async / await Mark , Perform asynchronous verification , In essence, promise There is no difference in asynchronous verification , Just use async / await Yes, you can get the results and verify them in the next step , Now, , Such methods may be more common .

// index.js
const asyncFetchData = () =>{
    return new Promise((resolve,reject)=>{
        resolve('fight');
    });
};
// index.test.js
test('test ajax', async () => {
    const data = await sum.asyncFetchData();
    expect(data).toBe('fight');
}); 
 Copy code 

If you expect an abnormal state, you can use catch Capture , The test of abnormal conditions is generally in the case of some bottom logic , Get the exception and execute the specific logic .

// index.js
const asyncErrorFetchData = ()=>{
    return new Promise((resolve,reject)=>{
        reject('error');
    });
}
// index.test.js
test('test ajax error', async () => {
    expect.assertions(1);
    try {
        const data = await sum.asyncErrorFetchData();
      } catch (e) {
        expect(e).toMatch('error');
    }
});  
 Copy code 

among , When performing exception testing, you need to add expect.assertions(1) Number of assertions , Otherwise, the test will not pass , This is jset Specially marked on the document . But when I tested it locally , After removing this stuff , The test can still pass . Maybe in some scenarios .

Use of hook function

Hook execution

When executing the test file again , If you need to perform special processing on the function, you can use the hook function before and after execution ,beforeEach and afterEach. The methods used are as follows :

beforeEach(() => {
    console.log('beforeEach')
});
afterEach(() => {
    console.log('afterEach')
});
test('adds 1 + 2 to equal 3', ()=>{
    expect(sum.sum(1,2)).toBeGreaterThan(2);
});
 Copy code 

Every execution of a test The function will execute once beforeEach and afterEach, If all functions need to be executed only once in some specific cases , have access to beforeAll and afterAll. that , In the execution of all test after , It will only be executed once beforeAll and afterAll.

Conditional execution hook

seeing the name of a thing one thinks of its function , It is to choose when to trigger the hook function , According to the need to use .

beforeAll(() => {
    console.log('beforeAll')
});
afterAll(() => {
    console.log('afterAll')
});
test('adds 1 + 2 to equal 3', ()=>{
    // expect(sum.sum(1,2)).toBe(3);
    expect(sum.sum(1,2)).toBeGreaterThan(2);
});
describe('child component', () => {
    // Applies only to tests in this describe block
    beforeEach(() => {
      console.log('child beforeEach')
    });
    test('adds 1 + 2 to equal 3', ()=>{
        // expect(sum.sum(1,2)).toBe(3);
        expect(sum.sum(1,2)).toBeGreaterThan(2);
    });
  });
 Copy code 

Here his output order is : First perform beforeAll , Next step child beforeEach , In execution afterAll. Another is to load in order , Sequential loading is to match according to the existing matching order , Use the official website here demo explain .

describe('outer', () => {
  console.log('describe outer-a');

  describe('describe inner 1', () => {
    console.log('describe inner 1');
    test('test 1', () => {
      console.log('test for describe inner 1');
      expect(true).toEqual(true);
    });
  });

  console.log('describe outer-b');

  test('test 1', () => {
    console.log('test for describe outer');
    expect(true).toEqual(true);
  });

  describe('describe inner 2', () => {
    console.log('describe inner 2');
    test('test for describe inner 2', () => {
      console.log('test for describe inner 2');
      expect(false).toEqual(false);
    });
  });

  console.log('describe outer-c');
});

// describe outer-a
// describe inner 1
// describe outer-b
// describe inner 2
// describe outer-c
// test for describe inner 1
// test for describe outer
// test for describe inner 2

 Copy code 

That's all jest Basic usage , The next article will summarize jest Advanced usage of .

copyright notice
author[GavinUI],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2021/08/20210827093948767i.html

Random recommended