Jest 常用匹配器
Jest 常用匹配器
toBe
toBe
使用 Object.is 判断是否严格相等。我理解为精准匹配
test ('测试10与10相匹配',()=>{// toBe 匹配引用地址相同expect(10).toBe(10)
})
toEqual
toEqual
递归检查对象或数组的每个字段。匹配相同的内容
test ('测试相匹配',()=>{const a = {one:1}expect(a).toEqual({one:1})
})
not
not
取反;所有的匹配器都可以使用 .not
取反:
test ('not 匹配器',()=>{// not 匹配取反const a = 1// a 不为假expect(a).not.toBeFalsy() // 通过
})test('Adding 1 + 1 does not equal 3', () => {expect(1 + 1).not.toBe(3)
})
toBeNull
toBeNull
只匹配 null。
test ('测试相匹配null',()=>{// toBe 匹配内容相同const a = undefindexpect(a).toBeNull() // 不通过,因为不是null
})
toBeUndefined
toBeUndefined
只匹配 undefined。
test ('测试相匹配undefind',()=>{// toBeUndefind 匹配内容相同const a = undefindexpect(a).toBeUndefind() // 通过
})
toBeDefined
toBeDefined
只匹配非 undefined。
test ('测试相匹配undefind',()=>{// toBeDefind 匹配是否定义过const a = undefindexpect(a).toBeDefind() // 不通过
})
toBeTruthy
toBeTruthy
只匹配真。
test ('测试相匹配toBeTruthy',()=>{// toBeTruthy 匹配是否为真const a = 1expect(a).toBeTruthy() // 通过
})
toBeFalsy
toBeFalsy
只匹配假。
test ('测试相匹配toBeFalsy',()=>{// toBeFalsy 匹配是否为假const a = 1expect(a).toBeFalsy() // 不通过
})
toBeGreaterThan
数字匹配器。toBeGreaterThan
实际值大于期望。
// 数字相关的匹配器
test ('toBeGreaterThan',()=>{// toBeGreaterThan 匹配 是否更大const a = 10expect(a).toBeGreaterThan(9) // 通过
})
toBeLessThan
数字匹配器。toBeLessThan
实际值小于期望值
test ('toBeLessThan',()=>{// toBeLessThan 匹配 是否更小const a = 10expect(a).toBeLessThan(11) // 通过
})
toBeLessThanOrEqual
数字匹配器。toBeLessThanOrEqual
实际值小于或等于期望值。
test ('toBeGreaterThanOrEqual',()=>{// toBeGreaterThanOrEqual 匹配 是否 大于或等于// toBeLessThanOrEqual 匹配 是否 小于或等于const a = 10expect(a).toBeGreaterThanOrEqual(10) // 通过
})
toBeCloseTo
数字匹配器。toBeCloseTo
比较浮点数的值,避免误差。对于比较浮点数的相等,应该使用 toBeCloseTo
test ('toBeCloseTo',()=>{// toBeCloseTo 匹配 是否 等于// 计算浮点数 就用这种const firstName = 0.1const secondName = 0.3expect(firstName + secondName).toEqual(0.4) // 不通过expect(firstName + secondName).toBeCloseTo(0.4) // 通过
})
toMatch
字符串匹配器。toMatch
正则匹配。
// 和string相关
test ('toMatch',()=>{// toMatch 匹配 字符串是否包含const str = 'http://www.dell-lee.com'expect(str).toMatch('dell') // 通过expect(str).toMatch(/dell-lee/) // 通过 正则也可以
})test('there is no I in team', () => {expect('team').not.toMatch(/I/);
});test('but there is a "stop" in Christoph', () => {expect('Christoph').toMatch(/stop/);
});
toHaveLength(number)
- 判断一个有长度的对象的长度
expect([1, 2, 3]).toHaveLength(3);
expect('abc').toHaveLength(3);
expect('').not.toHaveLength(5);
toContain(item)
数组匹配器。toContain
判断数组中是否包含指定项。
// Array ,Set
test ('toContain',()=>{// toContain 匹配 数组是否包含const str = ['dell','lee','imooc']expect(str).toContain('dell') // 通过// 写法2const str = ['dell','lee','imooc']const data = new Set(str)expect(data).toContain('dell') // 通过})const shoppingList = ['diapers','kleenex','trash bags','paper towels','beer',
];test('购物清单(shopping list)里面有啤酒(beer)', () => {expect(shoppingList).toContain('beer');
});
toContainEqual(item)
数组匹配器。- 判断数组中是否包含一个特定对象,类似 toEqual 与 toContain 的结合
function myBeverages() {return [{delicious: true, sour: false},{delicious: false, sour: true}]
}
test('is delicious and not sour', () => {const myBeverage = {delicious: true, sour: false};expect(myBeverages()).toContainEqual(myBeverage);
});
toMatchObject(object)
判断一个对象嵌套的 key 下面的 value 类型,需要传入一个对象。
const houseForSale = {bath: true,bedrooms: 4,kitchen: {amenities: ['oven', 'stove', 'washer'],area: 20,wallColor: 'white',},
};
const desiredHouse = {bath: true,kitchen: {amenities: ['oven', 'stove', 'washer'],wallColor: expect.stringMatching(/white|yellow/),},
};test('the house has my desired features', () => {expect(houseForSale).toMatchObject(desiredHouse);
});
toHaveProperty(keyPath, value)
对象匹配器。toHaveProperty(keyPath, value)
判断对象中是否包含指定属性。
// Object containing house features to be tested
const houseForSale = {bath: true,bedrooms: 4,kitchen: {amenities: ['oven', 'stove', 'washer'],area: 20,wallColor: 'white',},
};test('this house has my desired features', () => {// Simple Referencingexpect(houseForSale).toHaveProperty('bath');expect(houseForSale).toHaveProperty('bedrooms', 4);expect(houseForSale).not.toHaveProperty('pool');// Deep referencing using dot notationexpect(houseForSale).toHaveProperty('kitchen.area', 20);expect(houseForSale).toHaveProperty('kitchen.amenities', ['oven','stove','washer',]);expect(houseForSale).not.toHaveProperty('kitchen.open');// Deep referencing using an array containing the keyPathexpect(houseForSale).toHaveProperty(['kitchen', 'area'], 20);expect(houseForSale).toHaveProperty(['kitchen', 'amenities'],['oven', 'stove', 'washer'],);expect(houseForSale).toHaveProperty(['kitchen', 'amenities', 0], 'oven');expect(houseForSale).not.toHaveProperty(['kitchen', 'open']);
});// demo.js<ViewclassName="navigation-bar"style={{height: `${utils.navHeight}px`,color,backgroundColor}}>
</View>// demo.test.jsconst navBackEle = wrapper.find('.navigation-bar'); // 主体颜色配置expect(navBackEle.prop('style')).toHaveProperty('backgroundColor', '#32cb9d');
toBeInstanceOf
toBeInstanceOf
判断对象是否是某个类的实例,底层使用 instanceof。
toThrow
toThrow
判断是否抛出指定的异常。
// 异常情况的匹配const throwNewErrorFunc = ()=>{throw new Error('this is a new error')
}
test ('toThrow',()=>{// toThrow 匹配 是否异常expect(throwNewErrorFunc).toThrow() // 通过expect(throwNewErrorFunc).not.toThrow() // 不通过expect(throwNewErrorFunc).toThrow('this is a new error') // 通过expect(throwNewErrorFunc).toThrow(/this is a new error/) // 通过
})
toHaveBeenCalled()
- 用来判断一个函数是否被调用过
toHaveBeenCalled() 也有个别名是.toBeCalled()
,用来判断一个函数是否被调用过。
describe('drinkAll', () => {test('drinks something lemon-flavored', () => {const drink = jest.fn();drinkAll(drink, 'lemon');expect(drink).toHaveBeenCalled();});test('does not drink something octopus-flavored', () => {const drink = jest.fn();drinkAll(drink, 'octopus');expect(drink).not.toHaveBeenCalled();});
});
toHaveBeenCalledTimes(number)
和 toHaveBeenCalled 类似,判断函数被调用过几次。
test('drinkEach drinks each drink', () => {const drink = jest.fn();drinkEach(drink, ['lemon', 'octopus']);expect(drink).toHaveBeenCalledTimes(2);
});
toHaveBeenCalledWith(ecent)
事件调用的时候,他的参数
describe('Zero', () => {it('calls setCount with 0', () => {wrapper.find('#zero-count').props().onClick();expect(setState).toHaveBeenCalledWith(0);});});
toHaveBeenLastCalledWith
最后一次调用时,函数的参数匹配
describe('TripTypeChoose组件测试', () => {it('展示TripTypeChoose', () => {const propsEvent = jest.fn();const value = '1';const wrapper = shallow(<TripTypeChoose handelTicketChoice={propsEvent} singleTrip="0" formOrder={true} />);wrapper.find('[data-test="handelTicketDom"]').simulate('change', {detail: { value },});// 断言 change 事件参数为valueexpect(propsEvent).toHaveBeenLastCalledWith(value);expect(toJson(wrapper)).toMatchSnapshot();});
});
lastCalledWith
toBeCalledWith
toBeInstanceOf
toMatchSnapshot
toThrowError
toThrowErrorMatchingSnapshot
Jest 常用匹配器相关推荐
- 【Jest】笔记二:Matchers匹配器
一.前言 什么是匹配器? 我们可以把匹配器看成,testng断言,这么理解就可以了 二.常用的匹配器 test('two plus two is four', () => {expect(2 + ...
- Jest 测试框架 expect 和 匹配器 matcher 的设计原理解析
副标题:SAP Spartacus SSR 优化的单元测试分析之二 - 调用参数检测 源代码: it(`should pass parameters to the original engine in ...
- Jest测试框架入门之匹配器与测试异步代码
一.匹配器 1.对于一般的数字与字符串类型使用 toBe test('adds 1 + 2 to equal 3', () => {expect(1 + 2).toBe(3); });test( ...
- Mockito匹配器优先
这篇文章是意见. 让我们看一下Mockito中用于在Java中进行测试的verify方法. 示例: verify(myMock).someFunction(123) –期望在模拟ONCE上使用输入12 ...
- 过滤器匹配符包含单词_Hamcrest包含匹配器
过滤器匹配符包含单词 与Hamcrest 1.2相比 ,针对Matchers类的Hamcrest 1.3 Javadoc文档为该类的几种方法添加了更多文档. 例如,四个重载的contains方法具有更 ...
- Hamcrest匹配器常用方法总结
一.Hamcrest是什么? Hamcrest is a library of matchers, which can be combined in to create flexible expres ...
- SLAM Cartographer(13)基于Ceres库的扫描匹配器
SLAM Cartographer(13)基于Ceres库的扫描匹配器 1. 扫描匹配器 2. 残差计算 2.1. 平移残差 2.2. 角度残差 2.3. 占据空间残差 1. 扫描匹配器 通过< ...
- SLAM GMapping(6)扫描匹配器
SLAM GMapping(6)扫描匹配器 1. 扫描匹配 2. 爬山优化 2.1 寻优思路 2.2 爬山初始化 2.2 爬山过程 3. 似然度和匹配度 4. 地图更新 4.1. 更新有效区域 4.2 ...
- easymock参数_EasyMock参数匹配器
easymock参数 EasyMock argument matchers allow us to provide the flexible argument for matching when st ...
最新文章
- selenium+chromedriver爬取淘宝美食信息保存到MongoDB
- FBI发警告:留意联网汽车被黑客攻击风险
- javascript学习代码
- Thinkphp5内核大型程序员交流博客系统源码
- C#中(int),int.Parse,int.TryParse,Convert.ToInt32四则之间的用法
- 【OpenCv】cvWaitKey获取键盘值
- 数据库系统概论第五版 (第 1 章 绪论 ) 笔记
- 集合的相关概念(开闭、有界无界、内点边界点等)
- 给机器人罗宾写一封英语回信_小学英语人教(13版三起点)六年级上册Unit1
- Ubuntu 配置磁盘挂载到指定目录
- Springboot RabbitMQ
- python聊天室socket+tkinter_基于socket和tkinter的python网络聊天室程序
- H5表单validity各个属性对应
- loopback address 回送地址
- springboot2.0设置session失效时间需要使用Duration字符串
- Eclipse 开源详细介绍
- 关于 Android 平台开发相关的有哪些推荐书籍?
- 【java】序列化与反序列
- KMP算法——很详细的讲解
- 汽车充电系统开发解决方案
热门文章
- PCSX2的impossible blend释疑
- [Nginx]Ngnix基础
- TeamViewer账号未激活问题
- Struts2框架漏洞总结与复现(上) 含Struts2检测工具
- html背景音乐自动播放embed,怎样在网页中插入背景音乐(自动播放代码).doc
- 知识是不会让人自满的。 少年,只有名和利才会。
- 转载:Network 之三 Ethernet(以太网)物理介质(10Base、100Base-T、100Base-TX等)介绍
- 在冒险中打拼:教师到手机大亨的打拼路
- DDR,DDR2,DDR3区别
- 电解电容、钽电容、普通电容