• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
小码哥-倩倩
博客园    首页    新随笔    联系   管理    订阅  订阅

(七)Jest钩子函数作用域

一 、钩子函数的作用域

(1)、describe下都可以拥有自己的钩子函数,使用的钩子函数对自己的子describe的测试用例也适用。

(2)、每个子describe也可以设置自己需要的钩子函数,使用的钩子函数对自己的测试用例适用。

(3)、说明钩子函数是有作用域的,而且在describe的范围内,至于执行顺序是由外到内。

(4)、describe可以嵌套使用,一个describe中可以嵌套很多describe。

  示例代码如下:

import  Counter  from './counter.js'
let counter =null;
describe('钩子函数',()=>{
	beforeAll(()=>{
		console.log('生命周期---BeforeAll--在测试用例执行之前')
	})
	afterAll(()=>{
	
	})
	beforeEach(()=>{
		counter = new Counter();
	})
	afterEach(()=>{
	})
	describe('测试加法',()=>{
		beforeAll(()=>{
			console.log('生命周期---BeforeAll--在测试加法')
		})
		test('测试counter中addOne方法',()=>{
			counter.addOne();
			expect(counter.number).toBe(1)
		})
		test('测试counter中addTwo方法',()=>{
			counter.addTwo();
			expect(counter.number).toBe(2)
		})
	})
	describe('测试减法',()=>{
		beforeAll(()=>{
			console.log('生命周期---BeforeAll--在测试减法')
		})
		test('测试counter中minusOne方法',()=>{
			counter.minusOne();
			expect(counter.number).toBe(-1)
		})
	})
	
})

运行结果如下:

 

从运行结果上我们可以看出对应describe中钩子函数执行顺序。

二 、Jest的only修饰符

运用.only修饰符,它只会执行加上这个标识的测试用例,跳过其他的测试用例。

import  Counter  from './counter.js'
let counter =null;
describe('钩子函数',()=>{
	beforeEach(()=>{
		counter = new Counter();
	})
	describe('测试加法',()=>{
		test.only('测试counter中addOne方法',()=>{
			console.log('执行addOne')
			counter.addOne();
			expect(counter.number).toBe(1)
		})
		test('测试counter中addTwo方法',()=>{
			console.log('执行addTwo')
			counter.addTwo();
			expect(counter.number).toBe(2)
		})
	})
	describe('测试减法',()=>{
		test('测试counter中minusOne方法',()=>{
			console.log('减法minusOne')
			counter.minusOne();
			expect(counter.number).toBe(-1)
		})
	})
	
})

我们发现只有ddOne测试用例会执行,其他用例直接跳过。运行结果如下:

 

posted @ 2020-05-06 18:23  小码哥-倩倩  阅读(311)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3