DEV Community

Seyram Ofori
Seyram Ofori

Posted on

TIL; JavaScript Jest - matchers

matchers

  • matchers allow you to test values by comparing the actual value to the expected value
  • expect returns an expectation object. you call matchers on this object to achieve the comparison of actual to expected.
  • toBe matcher uses [Object.is] to test exact equality.
  • if you want to check the value of an object, use toEqual or toStrictEqual instead.
    • what does ‘check the value of an object’ mean?
  • toBe vs toEqual vs toStrictEqual. when to use which?
    • prefer toStrictEqual over toEqual, cos toEqual simply ignores undefined values
    • under which conditions would you want to ignore undefined values?
  • you can easily test the opposite of a matcher using .not. eg: expect(a+b).not.toStrictEqual(0)

truthiness

  • matchers that allow you to be specific about the kind of truthy value you want
  • there’s 5 of them
  • toBeNull matches only null
  • toBeUndefined matches only undefined
  • toBeDefined is the opposite of toBeUndefined
  • toBeTruthy matches anything that an if statement treats as true
  • toBeFalsy matches anything that an if statement treats as false
  • you should use the matcher that most precisely corresponds to what you want your code to be doing

numbers

  • there’s 7 matchers that can be used for numbers
  • toBeGreaterThan
  • toBeGreatherThanOrEqual
  • toBeLessThan
  • toBeLessThanOrEqual
  • toBe
  • toEqual
  • toBeCloseTo ; to be used for floating point equality. cos we don’t want a test to depend on a tiny rounding error.

    const value = 0.1 + 0.2;
    expect(value).toBe(0.3); // this won't work cos of rounding error
    expect(value).toBeCloseTo(0.3); // this works
    
  • toBe and toEqual are equivalent for numbers

strings

  • you can check strings against regular expressions with toMatch
    • expect('Christoph').toMatch(/stop/)

arrays and iterables

  • you can check if an array or iterable contains a particular item using toContain
    • expect(['diapers', 'paper towels']).toContain('paper towels');
  • JS iterables include the ff
    • string
    • array
    • TypedArray
    • Map
    • Set
    • Segments (returned by Intl, Segmenter, prototype, segment())

an iterable is defined by the fact that its prototype object implements an @@iterator method

exceptions

  • to test whether a particular function throws an error when it’s called, use toThrow
  • to check the error message, you can pass a regex to the toThrow() matcher
  • the function that throws an exception needs to be invoked within a wrapping function otherwise the toThrow() assertion will fail.

Top comments (0)