Catalog / Jest Cheatsheet
Jest Cheatsheet
A quick reference guide for Jest, a delightful JavaScript Testing Framework with a focus on simplicity.
Jest Basics
Installation & Setup
Installation:
|
Package.json Configuration: Add a test script to your
|
Running Tests:
|
Writing Basic Tests
Test Structure:
|
Used to group related tests.
|
The |
Matchers
|
Tests for exact equality using |
|
Tests for deep equality (for objects and arrays). |
|
Matches only |
|
Matches only |
|
The opposite of |
|
Matches anything that an |
|
Matches anything that an |
|
Tests if value is greater than number. |
Asynchronous Testing
Promises
Testing Promises: Return the promise from your test. Jest will wait for the promise to resolve.
|
|
Async/Await
Using
|
|
Callbacks
Using If you’re using callbacks, Jest provides a
|
Mocking
Mock Functions
Creating Mock Functions:
|
Mocking Modules:
|
Mocking Implementations
Define a custom implementation for the mock function.
|
Define a default return value for the mock.
|
Mocking Return Values
Mocks a promise that resolves to the specified value. Helpful for async functions.
|
Mocks a promise that rejects with the specified value.
|
Snapshot Testing
Basics
What are Snapshots? Snapshots capture the rendered output of a component at a specific point in time. Jest compares the current output with the stored snapshot to detect unexpected changes. |
|
Updating Snapshots: If a snapshot test fails due to an intentional change, you need to update the snapshot.
|
Inline Snapshots
Stores the snapshot directly in the test file.
|
Configuration
Snapshot Directory: Snapshots are typically stored in a |
Ignoring changes: It is possible to ignore certain parts of a snapshot. |