一、背景:
老师要求学习jest,但是官方文件内容较多且都是英文,有中文释义版本但是没涵盖全部API,因此自行整理一份详细API版本,部分配上我运行后的截图,最后给出示例。
二、介绍:
- Jest:目前最流行的前端测试框架,几乎国内所有的大型互联网公司都在使用。
- 官方文件快速入门 · Jest 中文文档 | Jest 中文网
三、Global API:
包含4个钩子函数,网上很多资料介绍钩子函数,在此简单写出示例,以及详细介绍除此之外的global API,如下:
编号 |
钩子函数 |
说明 |
示例 |
---|---|---|---|
1 |
beforeAll |
在所有测试用例运行test()之前,该函数只会执行一次,会先调用 beforeAll 钩子函数,在这期间可以做一些全局变量的初始化 |
beforeAll(()=>{ console.log('吃完饭后,走进了红浪漫洗浴') }) |
2 |
beforeEach |
每个测试用例执行之前,都会调用,类似 vue-router 的 beforeEach,这样每次测试都是一个全新的实例,各个用例之间互不干扰。 |
afterAll(()=>{ console.log('有钱人的生活就是这么的枯燥且寂寞') }) |
3 |
afterEach |
与beforeEach相反,每个测试用例执行之后,都会调用,类似 vue-router 的 beforeEach,这样每次测试都是一个全新的实例,各个用例之间互不干扰。 |
beforeEach(()=>{ console.log('给了300元钱后......') }) |
4 |
afterAll |
在所有测试用例运行test()完之后,会先调用 afterAll 钩子函数,该函数只会执行一次 |
afterEach(()=>{ console.log('完成后,我心满意足的坐在沙发上!!!') }) |
编号 | 函数名 | 释义 | 示例 |
---|---|---|---|
1 | describe | describe(name, fn) 创建一个将几个相关测试组合在一起的块 | const myBeverage = {
describe('my beverage', () => {
test('is not sour', () => {
|
2 | describe.each |
describe.each(table)(name, fn, timeout)允许编写一次测试套件并传入数据 |
describe.each([ |
3 | describe.only |
describe.only(name, fn) 如果您只想运行一个 describe 块,则可以使用 describe.only |
describe.only('my beverage', () => {
test('is not sour', () => {
describe('my other beverage', () => {
|
4 | describe.only.each |
|
describe.only.each([ test('will not be ran', () => {
|
5 | describe.skip |
|
describe('my beverage', () => {
test('is not sour', () => {
describe.skip('my other beverage', () => {
|
6 | describe.skip.each |
|
describe.skip.each([ test('will be ran', () => {
|
7 | test |
|
test('did not rain', () => {
expect(inchesOfRain()).toBe(0); }); |
8 | test.concurrent |
|