当前位置:网站首页>[jest] summary of the use of automated test jest
[jest] summary of the use of automated test jest
2022-06-24 05:09:00 【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)
});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})
});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()
});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)
});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/);
});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);
});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);
}); 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')
});
}); 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');
}); 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');
}
}); 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);
});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);
});
});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 2That's all jest Basic usage , The next article will summarize jest Advanced usage of .
边栏推荐
- What is the difference between a traditional data center and a cloud computing data center?
- Pg-pool-ii read / write separation experience
- Weak current engineer, 25g Ethernet and 40g Ethernet: which do you choose?
- Tencent cloud audio and video award-winning evaluation | leave online messages or submit evaluation, win Dajiang UAV /iphone/switch and other awards
- Automatically convert local pictures to network pictures when writing articles
- Introduction to vulnerability priority technology (VPT)
- Introduction to ebpf
- 解析90后创客教育的主观积极性
- How should a new data center be built?
- Functional advantages of industrial wireless router
猜你喜欢

Let children learn the application essence of steam Education

Hard core observation 553 AI needs to identify almost everyone in the world with hundreds of billions of photos

『渗透基础』Cobalt Strike基础使用入门_Cobalt Strike联动msfconsole

What is the new generation cloud computing architecture cipu of Alibaba cloud?

Leetcode question brushing (question 3) - the longest substring without repeated characters

少儿编程课程改革后的培养方式

Idea creates a servlet and accesses the 404 message

Leetcode (question 2) - adding two numbers

Training methods after the reform of children's programming course

Facebook internal announcement: instant messaging will be re integrated
随机推荐
Why do hybrid clouds exist?
4G industrial VPN router
Before creating an image, it is recommended to execute the following code to purify the image as an administrator
Build your unique online image
What is an ECS? ECS、BCC、CVM...
[leetcode daily question] push domino
Locating memory leaks with poolmon
Bi-sql - Select
Deep learning common optimizer summary
Performance comparison of JS loop traversal methods: for/while/for in/for/map/foreach/every
Network timeout configuration method when PR and push are proposed
Webmeng: create a website you are proud of
How to control CDN traffic gracefully in cloud development?
Weak current engineer, 25g Ethernet and 40g Ethernet: which do you choose?
Hard core JS: there may be a memory leak in your program
Shutter - how to copy certain elements from a map to a new map in dart/shutter?
What is a network domain name? What is the role of a domain name for an enterprise
Automatically convert local pictures to network pictures when writing articles
Tencent conference rest API x-tc-registered parameter policy update notification
Tencent cloud audio and video award-winning evaluation | leave online messages or submit evaluation, win Dajiang UAV /iphone/switch and other awards