lightsoutAlpha

no-test-state-in-hooks

Where a test's state is built.

Deterministic checkBlocks by default

The rule

Agents read this text as written when they write and review code.

Never build a test's state in a beforeEach. Build it in the setup factory, which each test calls:

  • Never keep test state, the subject under test included, in a let that a beforeEach reassigns. Return it from the setup factory as a const.
  • Set a mock's return value or implementation (mockReturnValue, mockResolvedValue, mockRejectedValue, mockImplementation) in the setup factory, never in a beforeEach.
  • Act and assert in the test, never in a beforeEach.

Then each test states its own arrangement, and none depends on what another left behind.

Examples

The check flags the incorrect code and passes the correct code.

Incorrect

subject.unit.test.ts
import { beforeEach, describe, expect, jest, test } from '@jest/globals';
const mockGetProfile = jest.fn<() => string>();
// Incorrect: the subject lives in a shared variable the hook reassigns, and the
// hook also sets the mock's return value and asserts, so the test below states
// none of its own arrangement.
let subject: string;
describe('subject', () => {
beforeEach(() => {
mockGetProfile.mockReturnValue('p.png');
subject = mockGetProfile();
expect(subject).toBe('p.png');
});
test('reads the profile', () => {
expect(subject).toBe('p.png');
});
});

Correct

subject.unit.test.ts
import { describe, expect, jest, test } from '@jest/globals';
const mockGetProfile = jest.fn<() => string>();
// Correct: the setup factory sets the mock's return value and returns the
// subject as a const, and the test acts and asserts.
const setupSubject = () => {
mockGetProfile.mockReturnValue('p.png');
return { subject: mockGetProfile() };
};
describe('subject', () => {
test('reads the profile', () => {
const { subject } = setupSubject();
expect(subject).toBe('p.png');
});
});

Configure

  • Block"blocking"Stops a run when a file the run changed breaks the rule.
    Default
  • Advise"advisory"Reports it and hands it to the refactor agent. Never stops a run.
  • Off"off"Not checked. Use it when your own linter already enforces the rule.

Add this to your lightsout.config.json, then change the value.

lightsout.config.json
{
"standards-rule-settings": {
"no-test-state-in-hooks": "blocking"
}
}

Packs that select it