matchers
- matchers allow you to test values by comparing the actual value to the expected value
-
expectreturns an expectation object. you call matchers on this object to achieve the comparison of actual to expected. -
toBematcher uses[Object.is]to test exact equality. - if you want to check the value of an object, use
toEqualortoStrictEqualinstead.- what does ‘check the value of an object’ mean?
-
toBevstoEqualvstoStrictEqual. when to use which?- prefer
toStrictEqualovertoEqual, costoEqualsimply ignores undefined values - under which conditions would you want to ignore undefined values?
- prefer
- 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
-
toBeNullmatches onlynull -
toBeUndefinedmatches onlyundefined -
toBeDefinedis the opposite oftoBeUndefined -
toBeTruthymatches anything that anifstatement treats as true -
toBeFalsymatches anything that anifstatement 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
toBeGreaterThantoBeGreatherThanOrEqualtoBeLessThantoBeLessThanOrEqualtoBetoEqual-
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 toBeandtoEqualare equivalent for numbers
strings
- you can check strings against regular expressions with
toMatchexpect('Christoph').toMatch(/stop/)
arrays and iterables
- you can check if an array or iterable contains a particular item using
toContainexpect(['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)