Skip to main content

Matchers

修饰符

目前Jest里面支持的修饰符有3个:

  • .not
  • .resolves
  • .rejects
test('test', () => {
expect(1 + 2).toBe(3)
expect(1 + 2).not.toBe(4)
})

Matchers

Jest内置了非常多的匹配器:

  • 常用匹配器。
  • 布尔值匹配器。
  • 数值匹配器。
  • 字符串匹配器。
  • 数组匹配器。
  • 异常匹配器。
  • 非对称匹配器。

常用匹配器

  • toBe, 使用Object.is比较值。
  • toEqual,可针对对象进行一个深度比较。
const can1 = {
flavor: 'grapefruit',
ounces: 12
}
const can2 = {
flavor: 'grapefruit',
ounces: 12
}

describe('the La Croix cans on my desk', () => {
test('have all the same properties', () => {
expect(can1).toEqual(can2)
})
test('are not the exact same can', () => {
expect(can1).not.toBe(can2)
})
})

布尔值匹配器

布尔值匹配器运行结果是一个布尔值,使用布尔值相关匹配器的时候一般是无需传参的。

test('boolean matcher', () => {
const n = null
expect(n).toBeFalsy()
expect(n).not.toBeTruthy()

const a = 0
expect(a).toBeFalsy()
expect(a).not.toBeTruthy()
})

布尔值相关的这种无参的匹配器,在Jest中还有好几个:

test('NO Parametetrs', () => {
const n = null
expect(n).toBeNull()
expect(n).toBeDefined()
expect(n).not.toBeUndefined()
const a = 0
expect(a).not.toBeNull()
expect(a).toBeDefined()
expect(a).not.toBeUndefined()
})

数值匹配器

常见的就是两个数值之间大小的比较,有大于、大于等于、小于、小于等于、等于之类的:

test('数值相关匹配器', () => {
const value1 = 4
// 大于
expect(value1).toBeGreaterThan(3)
// 大于等于
expect(value1).toBeGreaterThanOrEqual(4)
// 小于
expect(value1).toBeLessThan(5)
// 小于等于
expect(value1).toBeLessThanOrEqual(4)

// 下浮点数
const value2 = 0.1 + 0.2
// Expected: 0.3
// Received: 0.30000000000000004
// expect(value2).toBe(0.3)

expect(value2).toBeCloseTo(0.3)
// toBeCloseTo 还接受第二个参数,第二个参数用于指定位数,默认是两位
expect(0.302).toBeCloseTo(0.301)
expect(0.302).not.toBeCloseTo(0.301, 5)
})

字符串匹配器

toMatch可检查字符串是否和某一个正则表达式能够匹配上:

test('string', () => {
expect('this is a test').toMatch(/test/)
expect('this is a test').not.toMatch(/abc/)
})

数组匹配器

toContain可以判断一个数组是否包含某一项:

const shoppingList = ['milk', 'orange', 'rice']

test('Array', () => {
expect([1, 2, 3]).toContain(1)
// expect([1, 2, 3]).toContain('1')
expect('this is a test').toContain('test')
expect(new Set(shoppingList)).toContain('milk')
})

异常匹配器

有些时候需要测试某个函数调用之后是否会抛出异常,那么可以使用toThrow这个匹配器:

function compileCode() {
throw new Error('aaa you are using the wrong JDK bbb')
}

test('Exception', () => {
expect(() => compileCode()).toThrow()

expect(() => compileCode()).toThrow(Error)
expect(() => compileCode()).toThrow(
'you are using the wrong JDK'
)
expect(() => compileCode()).toThrow(/JDK/)
})

非对称匹配器

如上的匹配器,基本都是对称匹配器,而Jest中还存在一些非对称匹配器:

const arr = [1]
test('Array do not include item', () => {
// 希望 [2, 3, 4] 中不包含 arr 中的元素
expect([2, 3, 4]).toEqual(expect.not.arrayContaining(arr))
})

非对称匹配器,toEqual匹配器里面是一段类似于描述的信息。