Jest Matchers
For a given test like:
js
it("returns apple", () => {
const fruit = getFruit();
expect(fruit).toBe("apple");
})
Here the .toBe("apple")
is the matcher.
Some common matchers:
toBeUndefined
, which matches onlyundefined
toBeDefined
, which matches anything elsetoBeTruthy
,toBeFalsy
toMatch
, to check strings against regular expressionstoContain
, checking for items in arrays
See using matchers from the Jest documentation.
Floating point errors
JS infamously uses floating point arithmatic to handle decimal numbers. Meaning you can often be off by fractions of fractions.
To avoid this, use toBeCloseTo
. Signature of which looks like:
function toBeCloseTo(expected: number, actual: number, precision?: number = 2)
Where precision
is the number of decimal places to use for comparision. It defaults to 2 places.
See the Jest source for toBeCloseTo
jest-dom
Common DOM matchers like .toBeVisible()
or .toBeInTheDocument()
come from the companion library jest-dom.
To install, install jest-dom
to a dev dependency:
shell
npm install -D jest-dom
And then add an import to your Jest setup script:
js
import "@testing-library/jest-dom";
// Add to jest.config.[j|t]s if not there already:
setupFilesAfterEnv: ['<rootDir>/path/to/jest-setup.[j|t]s']