Jest Matchers
For a given test like:
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
Exceptions
To check for exceptions, you'll need to both wrap the excepting function in a anonymous function, and use toThrow
.
const iThrowErrors = () => {
throw new Error("Oh NO!");
}
it("throws errors", () => {
// This passes
expect(() => iThrowErrors()).toThrow():
// This also passes!
expect(() => iThrowErrors()).toThrow("Oh NO!"):
})
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:
npm install -D jest-dom
And then add an import to your Jest setup script:
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']