lightsoutAlpha

test-manual-mock-cleanup

Resetting mocks between tests.

Deterministic checkAdvises by default

The rule

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

Leave mock cleanup to the package's Jest config, clearMocks: true and restoreMocks: true. Never clean mocks by hand in a beforeEach, beforeAll, afterEach or afterAll: no jest.clearAllMocks(), jest.resetAllMocks(), jest.restoreAllMocks(), mockClear() or mockReset() there.

When the package's config lacks them, never add them. That changes every existing test in the package, so it is the repo owner's decision, not a test task's side effect. Instead:

  • Build fresh jest.fn() mocks, and a fresh subject, inside each setup factory call.
  • Reset a module-level mock that must persist, such as one a jest.mock factory reads, at the top of the setup factory with .mockReset(), and wire it again. Or assert on it only with toHaveBeenCalledWith, which earlier calls cannot fool, and never with not.toHaveBeenCalled.
  • Report the missing config.

Examples

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

Incorrect

subject.unit.test.ts
import { expect, describe, test, jest, beforeEach } from '@jest/globals';
const mockGetTimezone = jest.fn<() => string>();
describe('subject', () => {
beforeEach(() => {
jest.clearAllMocks();
});
test('reads the timezone', () => {
mockGetTimezone.mockReturnValue('UTC');
expect(mockGetTimezone()).toBe('UTC');
});
});

Correct

subject.unit.test.ts
import { expect, describe, test, jest } from '@jest/globals';
const mockGetCurrency = jest.fn<() => string>();
const setupCurrency = () => {
mockGetCurrency.mockReset();
mockGetCurrency.mockReturnValue('GBP');
return { currency: 'GBP' };
};
describe('subject', () => {
test('reads the currency', () => {
const { currency } = setupCurrency();
expect(mockGetCurrency()).toBe(currency);
});
});

Configure

  • Block"blocking"Stops a run when a file the run changed breaks the rule.
  • Advise"advisory"Reports it and hands it to the refactor agent. Never stops a run.
    Default
  • 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": {
"test-manual-mock-cleanup": "advisory"
}
}

Packs that select it