Jest Testing
A skill for writing Jest unit tests for JavaScript classes, and for the modules
and data files a project tests alongside them.
The conventions are split across the detail files below.
**Five of them are read in full before the first line of a test is written, in a new test file
or in one that already exists:**
structure.md, mocks.md and
prohibit.md. They hold the prohibitions no lint rule catches, so a
file written without them passes lint and passes its own tests while breaking this convention
throughout, and nothing anywhere reports it. The rest are read as the work reaches them.
Measured: tests written with only the first three read carried a jest.fn() standing in for a
collaborator and a spy planted on a class prototype — both forbidden in the two files left
unread, and neither reported by lint.
Notation convention: Throughout this skill, when we simply write
describe()/test()/expect(), each is a generic term that implies
the corresponding
.each()variant (describe()includesdescribe.each(),
test()includestest.each(), andexpect()includesexpect.each()).
Where the context is limited to one or the other specifically, that will be stated explicitly.
Also, use
test()/test.each()for test blocks and neverit()/it.each()
(
it()is easy to misread asif(); lint also enforcestestvia
jest/consistent-test-it; see eslint-jest-rules.md).
Core principle: don't cut coverage using implementation knowledge (QA stance)
Tests must be written so that they notice even if the implementation is wrong.
Using knowledge gained from reading the implementation to judge "this will always
be this value" or "this member is obvious" and then **omitting cases or members,
or collapsing them into a single test(), is a QA mistake**. What a test must
guarantee is not the implementation's internal circumstances, but the member's
contract (externally observable behavior) as a black box.
- Do not omit something because "the implementation is written this way so it's
fine." If you do, hard-coding or regressions can slip in without the test
noticing, which defeats the purpose of having a test at all.
- Example: for the instance getter
get Ctor () { return this.constructor },
collapsing it into a single test() that says "in the base class it's always
BoundCtorRegistry" would still pass even for the hard-coded implementation
return BoundCtorRegistry. Only by running the variable element (the
instance's type) through test.each() can you verify the contract
(structure.md).
- Example: don't skip testing a static property because "the memoization
pool is an implementation detail." Members that appear public should be
verified as part of the contract.
- Example: for a member that transforms a property/argument before using it
(escape / normalize / encode, etc.), don't test only with values for which the
transformation is a no-op. Always include **a value that actually exercises the
transformation** so that a broken transformation would be noticed
- When in doubt, err on the side of coverage. When trimming a member,
branch, or variable element, the justification must be "this input/state
cannot exist under the contract," never "because I know the implementation."
Run the test against the unchanged code first
**A test written for a change is run against the code as it stands, before the
change, and it has to fail there.** A test that passes against the unchanged
code is describing what the code already does — the one thing a test must not
be, and the shape a test takes when it is written by reading the very
implementation it is meant to check.
Measured on one such run: the new cases failed 19 and passed 8 against the
unchanged code, and all 27 passed once the code had changed.
- **The cases that pass against the unchanged code are the ones covering
behaviour the change does not touch**, and that is correct rather than a
defect. In the run above the 8 were the surface that already existed, whose
signature and behaviour the change left alone.
- So the run reports a split as well as a verdict: which of the new cases cover
new ground, and which are holding ground that was already held.
Core principle: don't put logic in test files
A test must consist only of assertions (expect()) that **check simple
input and output values**. Writing logic inside a test to prepare it is a
well-known anti-pattern. Test code itself is not verified, so if raw logic
written inside a test is wrong, nobody notices, and the reliability of the test
collapses.
- The only things allowed for use inside a test are things that **have already
been tested elsewhere and have guaranteed behavior** (already-tested classes,
factory methods, literal data, etc.). Do not write unverified transformations,
branches, or helper definitions.
- Inside
describe(), do not useif/ ternary /??/ short-circuit
evaluation / higher-order functions / forEach. Express repetition with
expect.each() from @openreachtech/jest-expect-each.
- The test is syntactic, not semantic. A call taking a function is a
higher-order function, and how short its body is, how obvious it looks or
how free of branching it happens to be does not enter into it:
errors.map(it => it.message) is as prohibited as any other. Asking whether
a particular case "really counts as logic" is the judgement this rule exists
to remove, and the answer arrived at is always yes.
- It covers the result as much as the preparation. The paragraph above
speaks of logic written to prepare a test, and reducing what a call
returned so that one assertion can compare it reads as outside that — which
is the route this rule is most often escaped through. A collection is
compared with expect.each(), never by mapping it down to something
toStrictEqual() accepts.
- See anti-pattern.md for details and examples.
Core principle: nothing but imports at file scope
**The only thing a test file may hold outside every describe() is its
imports.** A value, a class, a function, a schema — each is defined inside every
describe() that uses it, written out as many times as there are describe()
blocks that need it.
DRY does not apply to test code, and file scope is where it is refused most
plainly. A definition shared there cannot be changed for one member without
being read against the assumptions of every other describe() depending on it,
so it ends up copied and modified in place anyway — which is what defining it
per describe() does from the start. Shared state at file scope is also
untraceable to the blocks that rely on it, which is how one test contaminates
the next.
- **Two
describe()blocks needing the same value is the case this rule is
for**, not the exception to it. The cost of repeating the definition is
keystrokes; the cost of sharing it is that neither block can be read on its
own.
- See anti-pattern.md and
structure.md for the reasoning and examples.
Core principle: the case object has four property names, and no others
The element objects of cases carry override, input, tally and
expected. params and args are not among them and are never invented —
the argument passed to the subject under test is input.
- The set is closed, so a name that is not one of the four is wrong however well
it reads. The one addition allowed is a prefixed ~Cases property, on the
outer cases of a double loop.
- Which of the four applies, and the mechanical test separating
tallyfrom
input / expected, are in
- A repository full of
paramsis not a licence to write another. Test
files predating this convention record when they were written, and the
workflow convention settles what to follow where the code around you and a
convention disagree.
- A file carried over from elsewhere was written on the day it was carried.
What the exemption covers is a file that already stood, never content copied
into a new one: a port rewrites every line it moves, so the names it keeps are
names chosen now. Measured on one migration: test files arrived from a
repository with a different vocabulary, kept it, and passed lint — the
prohibition is deliberately not a rule — and they carry it still.
Core principle: index the first and second levels by definition name (class/member)
The nesting of describe() is fixed as level 1 = class name,
level 2 = member name. Do not write behavior (should ... / when ...)
directly at levels 1 or 2. Behavior must always go at level 3 or deeper,
following the order `describe(class) > describe(member) > describe(behavior) >
test()`.
- Why: One of the main purposes of a test is that **a human can later
look up the test for a given target**. When fixing a member in the
implementation, one must be able to reach the corresponding test with the
shortest path possible. Fixing levels 1 and 2 to definition names makes the
**implementation structure (class → member) directly the index key of the
tests**, so code and tests can be looked up one-to-one, in either direction.
- A behavior-first style (BDD-leaning writing that starts with
describe('should return 401 when ...')) reads well as a specification, but
it is slow to look up "where is the test for FooResolver#resolve()."
Because the class → member correspondence has no syntactic anchor, finding
the corresponding test from the implementation requires grepping the whole
file or tree exploration. This skill prioritizes lowering this **search
cost** through syntax.
- Prevents duplicate tests: if you cannot look up "where" the test for a
target member is, you cannot check whether an equivalent test already
exists, and similar tests end up added redundantly. This is especially
true when multiple people work on the same codebase — each person adds
tests without being able to find existing ones, which easily produces
duplication and coverage gaps. Indexing by definition name concentrates
"the test for this member is in exactly one place," letting you check
existing tests before adding new ones.
- As a consequence of this policy, the class-name
describe()is repeated
per member (one class describe() holds only one member). Even when
fast-scrolling a long file, the class name always sits directly above the
member describe(), so "which class, which member am I looking at" always
stays on screen (a syntactically achieved sticky header). We accept that the
class name is duplicated in Jest's output, in favor of human explorability.
- When the subject is not a class — a module of exported constants, or a
data file such as a message catalogue — the index rule still holds, but what
sits at each level changes. **A module reads level 1 off whatever it
default-exports**, and indexes below that by the kind of export and its name; a
data file is indexed by its path. **A reconciliation between two collections is
the one case where the rule cannot hold**, because neither side is the subject;
it is indexed by the relation instead. See
- For details on nesting structure and notation, see
Write comments in the code in English
- The language of a comment belongs to
/hoc-writing-language. It is read here for the comments written
into the tests generated under tests/ (// same reference / // neutral value; not under test
/ // all omitted → default; keep last, etc.) and into this skill's own examples: both are
English.
Removing a member takes two commits, implementation first
- When a member or a class is removed, the implementation goes out first and the tests that
covered it second. Why that order, and the other cases that take it, belong to
/hoc-git-commit-order.
Detail files
- directory.md — directory layout, import paths
- structure.md — structure of describe / test, and what may not be shared between them
- test-cases.md — data conventions for
cases - aaa-pattern.md — Arrange / Act / Assert
- mocks.md — mocks/stubs (inside Arrange, overridden with
jest.spyOn()), and which object the spy goes on - naming.md — variable names, and the closed set of
caseselement properties (override/input/tally/expected) - types.md — type annotations and type resolution
- anti-pattern.md — no logic in tests (forbidden syntax, extracted helpers), and no DRY — nothing but imports at file scope
- prohibit.md — prohibited items (forbidden matchers, etc.)
- eslint-jest-rules.md — ESLint (jest plugin) mapping (follow it and
npm run lintpasses; intentionally relaxed rules)