Jest
Last updated
Was this helpful?
Last updated
Was this helpful?
No testing solution out there is perfect. That said, jest is an excellent unit testing option which provides great TypeScript support.
Note: We assume you start off with a simple node package.json setup. Also all TypeScript files should be in a
src
folder which is always recommended (even without Jest) for a clean project setup.
Install the following using npm:
Explanation:
Install jest
framework (jest
)
Install the types for jest
(@types/jest
)
Install the TypeScript preprocessor for jest (ts-jest
) which allows jest to transpile TypeScript on the fly and have source-map support built in.
Save all of these to your dev dependencies (testing is almost always a npm dev-dependency)
Add the following jest.config.js
file to the root of your project:
Explanation:
We always recommend having all TypeScript files in a src
folder in your project. We assume this is true and specify this using the roots
option.
The transform
config just tells jest
to use ts-jest
for ts / tsx files.
The testRegex
tells Jest to look for tests in any __tests__
folder AND also any files anywhere that use the (.test|.spec).(ts|tsx)
extension e.g. asdf.test.tsx
etc.
The moduleFileExtensions
tells jest to recognize our file extensions. This is needed as we add ts
/tsx
into the defaults (js|jsx|json|node
).
Run npx jest
from your project root and jest will execute any tests you have.
Add package.json
:
This allows you to run the tests with a simple npm t
.
And even in watch mode with npm t -- --watch
.
npx jest --watch
For a file foo.ts
:
A simple foo.test.ts
:
Notes:
Jest provides the global test
function.
Jest comes prebuilt with assertions in the form of the global expect
.
Jest has built-in async/await support. e.g.
Enzyme allows you to test react components with dom support. There are three steps to setting up enzyme:
Install enzyme, types for enzyme, a better snapshot serializer for enzyme, enzyme-adapter-react for your react version npm i enzyme @types/enzyme enzyme-to-json enzyme-adapter-react-16 -D
Add "snapshotSerializers"
and "setupTestFrameworkScriptFile"
to your jest.config.js
:
Create src/setupEnzyme.ts
file.
Now here is an example react component and test:
checkboxWithLabel.tsx
:
checkboxWithLabel.test.tsx
:
Built-in assertion library.
Great TypeScript support.
Very reliable test watcher.
Snapshot testing.
Built-in coverage reports.
Built-in async/await support.