乐闻世界logo
搜索文章和话题

What are the test matchers in Jest? How to use custom matchers?

2月21日 15:57

Jest provides various test matchers to verify different conditions:

Equality Matchers:

  • toBe(value): Strict equality (===)
  • toEqual(value): Deep equality
  • toStrictEqual(value): Strict deep equality (including undefined properties)
  • toMatchObject(object): Partial object matching

Truthiness Matchers:

  • toBeNull(): Matches only null
  • toBeUndefined(): Matches only undefined
  • toBeDefined(): Not undefined
  • toBeTruthy(): Truthy values
  • toBeFalsy(): Falsy values

Number Matchers:

  • toBeGreaterThan(number): Greater than
  • toBeGreaterThanOrEqual(number): Greater than or equal
  • toBeLessThan(number): Less than
  • toBeLessThanOrEqual(number): Less than or equal
  • toBeCloseTo(number, precision): Floating point approximate equality

String Matchers:

  • toMatch(regexp | string): Matches regex or string
  • toContain(item): Contains element or substring

Array Matchers:

  • toContain(item): Contains element
  • toContainEqual(item): Contains equal element
  • toHaveLength(number): Array length
  • toBeArray(): Is an array

Object Matchers:

  • toHaveProperty(keyPath, value): Has specific property
  • toMatchObject(object): Partial object matching

Function Matchers:

  • toHaveBeenCalled(): Was called
  • toHaveBeenCalledWith(...args): Called with specific arguments
  • toHaveBeenCalledTimes(n): Number of calls
  • toHaveReturned(): Has return value
  • toHaveReturnedWith(value): Returned specific value

Exception Matchers:

  • toThrow(error?): Throws error
  • toThrowErrorMatchingSnapshot(): Error snapshot

Custom Matchers:

javascript
expect.extend({ toBeWithinRange(received, floor, ceiling) { const pass = received >= floor && received <= ceiling; return { pass, message: () => pass ? `expected ${received} not to be within range ${floor}-${ceiling}` : `expected ${received} to be within range ${floor}-${ceiling}` }; } }); test('number within range', () => { expect(100).toBeWithinRange(90, 110); });

Negation Matchers: All matchers can be negated using .not:

javascript
expect(value).not.toBe(42); expect(array).not.toContain('item');
标签:Jest