Jest 中的匹配器
1. toBe
toBe : js 中的绝对相同 === 三个等号
2. toEqual
toEqual :是"相等",不是"相同"
test('toBe', () => {
const a = {name: 'li'}
expect(a).toBe({name: 'li'})
})
test('toEqual', () => {
const a = {name: 'li'}
expect(a).toEqual({name: 'li'})
})
toBe 报错,toEqual 通过
根据对象来说,进行比较 是 相等 不是相同(存储空间不同,引用地址相同)
3. toBeNull
匹配是否是Null
test('toBeNull-1', () => {
const a = {name: 'li'}
expect(a).toBeNull()
})
test('toBeNull-2', () => {
const a = null
expect(a).toBeNull()
})
第一个报错 第二个通过
4. toBeUndefined
匹配是否是undefined
test('toBeUndefined-2', () => {
const a = undefined
expect(a).toBeUndefined()
})
test('toBeUndefined-2', () => {
const a = 1
expect(a).toBeUndefined()
})
第一个通过,第二个报错
5. toBeTruthy
是 true 验证通过,是 false 验证不通过
test('toBeTruthy-1', () => {
const a = 1
expect(a).toBeTruthy()
})
test('toBeTruthy-2', () => {
const a = 0
expect(a).toBeTruthy()
})
6. toBeFalsy
是false通过,是true不通过
test('toBeFalsy-1', () => {
const a = 0
expect(a).toBeFalsy()
})
test('toBeFalsy-2', () => {
const a = '9999'
expect(a).toBeFalsy()
})
7. toBeGreaterThan
相当于大于号,大于 true 小于不通过
如果不是数字的话也会校验不通过
test('toBeGreaterThan', () => {
const a = 9999
expect(a).toBeGreaterThan(1)
})
通过~
test('toBeGreaterThan', () => {
const a = 9999
expect(a).toBeGreaterThan(100000)
})
不通过
8. toBeLessThan
是否小于,小于true,大于不通过
test('toBeLessThan', () => {
const a = 9999
expect(a).toBeLessThan(100000)
})
通过
test('toBeLessThan', () => {
const a = 9999
expect(a).toBeLessThan(1000)
})
不通过
9. toBeGreaterThanOrEqual
大于等于通过,否则不通过
// 过
test('toBeGreaterThanOrEqual', () => {
const a = 1000
expect(a).toBeGreaterThanOrEqual(1000)
})
// 过
test('toBeGreaterThanOrEqual', () => {
const a = 100000
expect(a).toBeGreaterThanOrEqual(1000)
})
// 不通过
test('toBeGreaterThanOrEqual', () => {
const a = 999
expect(a).toBeGreaterThanOrEqual(1000)
})
10. toBeLessThanOrEqual
小于等于通过,否则不通过
// 不过
test('toBeLessThanOrEqual', () => {
const a = 9999
expect(a).toBeLessThanOrEqual(1000)
})
// 过
test('toBeLessThanOrEqual', () => {
const a = 999
expect(a).toBeLessThanOrEqual(1000)
})
// 过
test('toBeLessThanOrEqual', () => {
const a = 1000
expect(a).toBeLessThanOrEqual(1000)
})
11. toBeCloseTo
是否接近相等,由于js存在浮点计算,所以这个是用来校验是否接近相等
// 不通过
test('toBeEqual', () => {
expect(0.1 + 0.2).toBeEqual(0.3)
})
// 通过
test('toBeCloseTo', () => {
expect(0.1 + 0.2).toBeCloseTo(0.3)
})
12. toMatch
字符串匹配,某个字符串中是否含有某个子串
// 通过
test('toMatch', () => {
const str = '张三王五李四'
expect(str).toMatch('王五')
})
// 不通过
test('toMatch', () => {
const str = '张三王5李四'
expect(str).toMatch('王五')
})
13. toContain
数组中是否包含某一项
// 通过
test('toContain', () => {
const str = ['张三', '王五', '李四']
expect(str).toContain('王五')
})
// 不通过
test('toContain', () => {
const str = ['张三', '王五', '李四']
expect(str).toContain('王')
})
14. .not.toThrow
不抛出异常通过,抛出异常不通过
.not. 匹配器
// 不通过
const throwError = () => {
throw new Error('this is a error')
}
test('toContain', () => {
expect(throwError).not.toThrow()
})
// 通过
const throwErrorNot = () => {
return 1
}
test('toContain', () => {
expect(throwErrorNot).not.toThrow()
})