{"dataset":{"id":"00000000-0000-0000-0000-000000000047","slug":"jest-best-practices","name":"Jest best practices","description":"Source-linked guidance on Jest testing fundamentals: expect matchers, mock functions and modules, setup and teardown hooks, snapshot testing, and asynchronous tests. Scoped to Jest; not a general JavaScript testing corpus.","visibility":"public","version":1,"documentCount":5,"publisher":"Koskamo editorial","license":"Original summaries; linked sources retain their own terms.","reviewedAt":"2026-10-04T00:00:00.000Z","readOnly":true,"createdAt":"2026-10-04T00:00:00.000Z","updatedAt":"2026-10-04T00:00:00.000Z"},"total":5,"documents":[{"title":"Testing asynchronous code","sourceUrl":"https://jestjs.io/docs/asynchronous","text":"Asynchronous code needs Jest to know when it has completed before moving on to another test. The simplest form returns a promise from the test — Jest waits for it to resolve, and a rejection fails the test. The equivalent logic uses an async function passed to test with await before each call, optionally combined with .resolves or .rejects: await expect(fetchData()).rejects.toMatch('error'). Always return or await the promise; omitting either lets the test complete before the promise settles. When asserting rejections with .catch, add expect.assertions to verify the assertion count, otherwise a fulfilled promise would not fail the test. For callback-style APIs, declare a single done parameter and Jest waits until done is called; if done() never runs, the test fails with a timeout error, so wrap expect in try/catch and pass caught errors to done(error) to avoid opaque timeouts. Jest throws an error if one test both takes done and returns a promise, as a precaution against memory leaks. None of these forms is superior; mix and match them across a codebase or within a single file. Scope: Jest. Reviewed October 4, 2026.","id":"jest-best-practices:Testing asynchronous code","version":1,"createdAt":"2026-10-04T00:00:00.000Z","updatedAt":"2026-10-04T00:00:00.000Z"},{"title":"Snapshot testing","sourceUrl":"https://jestjs.io/docs/snapshot-testing","text":"Snapshot tests make sure your UI does not change unexpectedly: render a component with a test renderer into a serializable value, assert it with expect(container.firstChild).toMatchSnapshot(), and Jest compares it against the reference snapshot file stored alongside the test, failing when the two do not match. Commit snapshot artifacts alongside code changes and review them in code review; Jest uses pretty-format to keep them human-readable. After an intentional implementation change, regenerate with jest --updateSnapshot (or the equivalent -u flag), which re-records every failing snapshot — so fix genuine bugs first to avoid recording snapshots of buggy behavior — narrow regeneration to matching tests with --testNamePattern, or step through failures interactively in watch mode. Inline snapshots via .toMatchInlineSnapshot() write values back into the test source; Jest writes them by default and delegates to prettier when the project uses it. For generated fields like IDs and dates that would fail every run, pass property matchers such as expect.any(Date), which are checked before the snapshot is written and stored in place of the received value. Scope: Jest. Reviewed October 4, 2026.","id":"jest-best-practices:Snapshot testing","version":1,"createdAt":"2026-10-04T00:00:00.000Z","updatedAt":"2026-10-04T00:00:00.000Z"},{"title":"Setup and teardown hooks","sourceUrl":"https://jestjs.io/docs/setup-teardown","text":"For setup work repeated across many tests, use beforeEach and afterEach hooks; both handle asynchronous code the same ways tests do, by taking a done parameter or returning a promise. For setup needed only once at the beginning of a file, Jest provides beforeAll and afterAll. Top-level before* and after* hooks apply to every test in the file, while hooks declared inside a describe block apply only to tests within that block, and the top-level beforeEach runs before the beforeEach inside the describe block. Jest executes all describe handlers in a test file before any actual tests, which is another reason to do setup inside before* and after* handlers rather than inside describe blocks; once the describe blocks complete, Jest runs all tests serially in the order encountered by default. If a test is failing, check whether it fails as the only test that runs by temporarily using test.only; a test that fails in a suite but passes alone usually means shared state from another test is interfering, often fixable by clearing state with beforeEach. Scope: Jest. Reviewed October 4, 2026.","id":"jest-best-practices:Setup and teardown hooks","version":1,"createdAt":"2026-10-04T00:00:00.000Z","updatedAt":"2026-10-04T00:00:00.000Z"},{"title":"Mock functions and module mocking","sourceUrl":"https://jestjs.io/docs/mock-functions","text":"Mock functions test the links between code by erasing a function's real implementation while capturing calls and their parameters, capturing constructor instances created with new, and allowing test-time configuration of return values. Create one directly with jest.fn for use in test code, or write a manual mock to override a module dependency. Every mock exposes a .mock property recording calls and results, the this value per call (mock.contexts), constructor instantiations (mock.instances), and the last call's arguments (mock.lastCall). Queue return values with mockReturnValueOnce and mockReturnValue, or replace behavior with mockImplementation and one-shot mockImplementationOnce; when the one-shot queue empties, the default implementation from jest.fn runs. For modules, jest.mock('axios') automatically mocks the dependency so axios.get.mockResolvedValue(resp) injects a fake response without hitting the API, and a jest.mock factory can spread jest.requireActual to mock only part of a module. Keep logic out of mocked functions that are not directly under test. Scope: Jest. Reviewed October 4, 2026.","id":"jest-best-practices:Mock functions and module mocking","version":1,"createdAt":"2026-10-04T00:00:00.000Z","updatedAt":"2026-10-04T00:00:00.000Z"},{"title":"Asserting values with expect matchers","sourceUrl":"https://jestjs.io/docs/expect","text":"expect is used with a matcher function to assert something about a value: pass the value your code produces to expect, and the correct value to the matcher. The .not modifier tests the opposite, and .resolves or .rejects unwrap fulfilled or rejected promises so any other matcher can be chained. Use .toBe for primitive values or referential identity — it calls Object.is — but not for floating-point numbers; use .toBeCloseTo there. Use .toEqual for deep equality of object instances, noting it ignores keys with undefined properties, undefined array items, array sparseness, and type mismatch; use .toStrictEqual when those differences matter. Asymmetric matchers such as expect.any(constructor), expect.arrayContaining, expect.objectContaining, and expect.stringMatching make individual fields flexible. expect.assertions(number) and expect.hasAssertions() verify assertions actually ran, expect.extend registers custom matchers, and jest-extended offers community-maintained additions. With TypeScript, explicitly import { expect, jest, test } from '@jest/globals'. Scope: Jest. Reviewed October 4, 2026.","id":"jest-best-practices:Asserting values with expect matchers","version":1,"createdAt":"2026-10-04T00:00:00.000Z","updatedAt":"2026-10-04T00:00:00.000Z"}]}