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

What are the common assertion methods in Jest? How to use expect and matchers?

2月21日 15:57

Jest provides rich assertion methods, primarily used through the expect() function combined with matchers:

Common Matchers:

Equality Matchers:

  • toBe(value): Strict equality (using ===)
  • toEqual(value): Deep equality (recursively compares objects and arrays)
  • toMatchObject(object): Partial object property matching
  • toStrictEqual(value): Strict deep equality (including undefined properties)

Truthiness Matchers:

  • toBeNull(): Matches only null
  • toBeUndefined(): Matches only undefined
  • toBeDefined(): Not undefined
  • toBeTruthy(): Truthy values (not false, 0, "", null, undefined, NaN)
  • 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

Async Matchers:

  • resolves: Promise resolves
  • rejects: Promise rejects

Examples:

javascript
expect(2 + 2).toBe(4); expect({ name: 'John' }).toEqual({ name: 'John' }); expect(null).toBeNull(); expect(10).toBeGreaterThan(5); expect('hello').toMatch(/ell/);
标签:Jest