当前位置:网站首页>[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 .
边栏推荐
- How to create a virtual machine on vSphere client -- a reliable virtual machine creation tutorial
- CTF learning notes 18:iwesec file upload vulnerability-03-content-type filtering bypass
- cuDNN installation
- How to control CDN traffic gracefully in cloud development?
- Jimureport building block report - what problems does the layout design solve?
- Jimureport building block report - expression introduction
- Build your unique online image
- Disaster recovery series (IV) - disaster recovery construction of business application layer
- SAP mts/ato/mto/eto topic 8: ATO mode 2 d+ empty mode strategy 85
- The principle of defer keyword in go
猜你喜欢
![[leetcode daily question] push domino](/img/81/1c31e97d9a245816514bcf47c92107.jpg)
[leetcode daily question] push domino

CTF learning notes 17:iwesec file upload vulnerability-02 file name filtering bypass

SAP mts/ato/mto/eto topic 10: ETO mode q+ empty mode unvalued inventory policy customization

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

Training methods after the reform of children's programming course

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

Let children learn the application essence of steam Education

014_ TimePicker time selector

Analyzing the superiority of humanoid robot in the post human era

解析后人类时代类人机器人的优越性
随机推荐
Find the current index of gbase 8C database?
Bi-sql order by
What are clustering, distribution, and microservices?
Zhang Xiaodan, chief architect of Alibaba cloud hybrid cloud: evolution and development of government enterprise hybrid cloud technology architecture
CTF learning notes 17:iwesec file upload vulnerability-02 file name filtering bypass
Understanding OAuth 2.0
Tencent conference rest API x-tc-registered parameter policy update notification
MySQL cases MySQL find out who holds the row lock (RC)
Shuttle global levitation button
Training methods after the reform of children's programming course
『渗透基础』Cobalt Strike基础使用入门_Cobalt Strike联动msfconsole
Svg quick start small white article
Introduction to vulnerability priority technology (VPT)
Jimureport building block report - what problems does the layout design solve?
oracle数据库提示无操作权限的问题
Activity recommendation | cloud native community meetup phase VII Shenzhen station begins to sign up!
Elfk service setup
Three methods of local storage
Shopify background XSS storage vulnerability
What is required for domain name filing and how to select an enterprise domain name