Jest测试初学(五)--Jest中的钩子函数

Jest中的钩子函数相当于生命周期函数,在执行测试用例时,有先后调用的顺序。

一 Jest常用的钩子函数

beforeAll 在测试用例执行之前运行
beforeEach 在每一个测试用例执行之前运行

afterAll 在测试用例执行结束之后运行
afterEach 在每一个测试用例执行之后运行

import Counter from './Counter';

let  counter = null;
//在测试之前对一些内容进入初始化,使用jest的钩子函数
beforeAll(() => {
    console.log('生命周期---BeforeAll--在测试用例执行之前')
})

beforeEach(() => {
    console.log('生命周期---BeforeEach--在每一个测试用例执行之前');
    //实例化对象
    counter = new Counter();
})

afterEach(() => {
    console.log('生命周期---AfterEach--在每一个测试用例执行之后');
})

afterAll(()=> {
    console.log('生命周期---AfterAll--在测试用例执行结束之后')
})

test('测试Counter中的 addOne方法',()=>{
    console.log('测试Counter中的 addOne方法');
    counter.addOne();
    expect(counter.number).toBe(1);
});

test('测试Counter中的 addTwo方法',()=>{
    console.log('测试Counter中的 addTwo方法');
    counter.addTwo();
    expect(counter.number).toBe(2);
});

test('测试Counter中的 minusOne方法',()=>{
    console.log('测试Counter中的 minusOne方法');
    counter.minusOne();
    expect(counter.number).toBe(-1);
});

test('测试Counter中的 minusTwo方法',()=>{
    console.log('测试Counter中的 minusTwo方法');
    counter.minusTwo();
    expect(counter.number).toBe(-2);
});

Jest钩子函数

二 对测试用例进行分组

与mocha的语法相似,运用describe语法,第一个参数编写测试用例的名字,第二个参数编写需要执行的测试用例。

import Counter from './Counter';

describe('Counter的测试代码', () => {
    let  counter = null;
    //在测试之前对一些内容进入初始化,使用jest的钩子函数
    beforeAll(() => {
        console.log('生命周期---BeforeAll--在测试用例执行之前')
    })
    
    beforeEach(() => {
        console.log('生命周期---BeforeEach--在每一个测试用例执行之前');
        //实例化对象
        counter = new Counter();
    })
    
    afterEach(() => {
        console.log('生命周期---AfterEach--在每一个测试用例执行之后');
    })
    
    afterAll(()=> {
        console.log('生命周期---AfterAll--在测试用例执行结束之后')
    })
    
    describe('测试增加相关的代码', () => {
        test('测试Counter中的 addOne方法',()=>{
            console.log('测试Counter中的 addOne方法');
            counter.addOne();
            expect(counter.number).toBe(1);
        });
        
        test('测试Counter中的 addTwo方法',()=>{
            console.log('测试Counter中的 addTwo方法');
            counter.addTwo();
            expect(counter.number).toBe(2);
        });
    });
    
    describe('测试减少相关的代码', () => {
        test('测试Counter中的 minusOne方法',()=>{
            console.log('测试Counter中的 minusOne方法');
            counter.minusOne();
            expect(counter.number).toBe(-1);
        });
        
        test('测试Counter中的 minusTwo方法',()=>{
            console.log('测试Counter中的 minusTwo方法');
            counter.minusTwo();
            expect(counter.number).toBe(-2);
        });
    });    
});

describe测试返回的信息有进行分组

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值