@noctcore/eslint-plugin-code-quality 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,108 @@
1
+ # `noctcore-code-quality/fake-timers-must-be-restored`
2
+
3
+ > A file that installs fake timers must restore real ones.
4
+
5
+ Ported from [tsforge](https://github.com/boringstack-xyz/tsforge) (MIT). See
6
+ [THIRD_PARTY_NOTICES.md](../../THIRD_PARTY_NOTICES.md).
7
+
8
+ ## Why
9
+
10
+ `jest.useFakeTimers()` / `vi.useFakeTimers()` replace the global clock. Without a matching
11
+ `useRealTimers()` the fake clock leaks into later tests in the same worker, and those tests fail or,
12
+ worse, pass for the wrong reason, depending on file order.
13
+
14
+ ## What it flags
15
+
16
+ Every call to a `fakeTimerMethods` method (`useFakeTimers` by default, as `name()` or `obj.name()`)
17
+ in a file with no call to a `restoreTimerMethods` method, unless the restore lives in a shared suite
18
+ the file runs.
19
+
20
+ ### Shared suites
21
+
22
+ A contract suite often owns the restore: the spec installs fake timers inside a helper it hands to
23
+ the suite, and the suite restores them in its own `afterEach`.
24
+
25
+ ```ts
26
+ // provider.contract-suite.ts
27
+ export function runProviderContract(subject: Subject): void {
28
+ describe('provider contract', () => {
29
+ afterEach(() => jest.useRealTimers());
30
+ // ...
31
+ });
32
+ }
33
+
34
+ // fake-provider.contract.spec.ts
35
+ import { runProviderContract } from './provider.contract-suite';
36
+
37
+ const advancePastDeadline = () => {
38
+ jest.useFakeTimers();
39
+ jest.setSystemTime(Date.now() + 86_400_000);
40
+ };
41
+
42
+ runProviderContract({ advancePastDeadline });
43
+ ```
44
+
45
+ With `followImportedSuites` on (the default), the rule follows each relative import whose binding the
46
+ file calls (`runProviderContract(...)` or `suite.run(...)`), resolves it on disk (`.ts`, `.tsx`,
47
+ `.mts`, `.cts`, `.js`, `.jsx`, `.mjs`, `.cjs`, or a directory `index`), and accepts a restore call
48
+ in that module's source. The check is one level deep and text-based. An import that is only
49
+ re-exported, never called, does not count.
50
+
51
+ For a suite the rule cannot resolve (a path alias or a workspace package), name it in
52
+ `sharedSuiteModules`.
53
+
54
+ ```ts
55
+ // Bad
56
+ beforeEach(() => {
57
+ vi.useFakeTimers();
58
+ });
59
+
60
+ it('expires the session', () => {
61
+ vi.advanceTimersByTime(60_000);
62
+ expect(session.isExpired()).toBe(true);
63
+ });
64
+ ```
65
+
66
+ ```ts
67
+ // Good
68
+ beforeEach(() => {
69
+ vi.useFakeTimers();
70
+ });
71
+
72
+ afterEach(() => {
73
+ vi.useRealTimers();
74
+ });
75
+
76
+ it('expires the session', () => {
77
+ vi.advanceTimersByTime(60_000);
78
+ expect(session.isExpired()).toBe(true);
79
+ });
80
+ ```
81
+
82
+ ## Options
83
+
84
+ | Option | Type | Default | Meaning |
85
+ | --- | --- | --- | --- |
86
+ | `fakeTimerMethods` | `string[]` | `["useFakeTimers"]` | Methods that install fake timers. |
87
+ | `restoreTimerMethods` | `string[]` | `["useRealTimers"]` | Methods that restore real timers. One call anywhere in the file satisfies the rule. |
88
+ | `followImportedSuites` | `boolean` | `true` | Accept a restore found in a relative module this file imports and calls. |
89
+ | `sharedSuiteModules` | `string[]` (globs) | `[]` | Import specifiers trusted to restore timers when the file imports and calls them. Supports `*`, `**`, `?` and `{a,b}`. |
90
+
91
+ ```js
92
+ 'noctcore-code-quality/fake-timers-must-be-restored': ['error', {
93
+ fakeTimerMethods: ['useFakeTimers', 'install'],
94
+ restoreTimerMethods: ['useRealTimers', 'uninstall'],
95
+ sharedSuiteModules: ['@acme/testing/*-suite'],
96
+ }]
97
+ ```
98
+
99
+ ## Caveats
100
+
101
+ Reading an imported suite from disk means an edit to the suite alone does not invalidate
102
+ `eslint --cache` for the spec. The rule caches each suite's source by modification time within one
103
+ process.
104
+
105
+ ## When not to use it
106
+
107
+ If your runner restores timers globally (for example a setup file with a global `afterEach` that
108
+ calls `useRealTimers()`).
@@ -0,0 +1,82 @@
1
+ # `noctcore-code-quality/no-conditional-expect`
2
+
3
+ > An `expect()` that may not run lets a broken test pass.
4
+
5
+ Ported from [tsforge](https://github.com/boringstack-xyz/tsforge) (MIT). See
6
+ [THIRD_PARTY_NOTICES.md](../../THIRD_PARTY_NOTICES.md).
7
+
8
+ ## Why
9
+
10
+ An assertion inside an `if`, a `switch` case, a ternary, a `&&` / `||` / `??` or a `catch` only runs
11
+ when that branch is taken. When the code under test changes so the branch is skipped, the test
12
+ passes with zero assertions. The classic case is `try { await f(); } catch (e) { expect(e)... }`:
13
+ if `f` stops throwing, the test goes green.
14
+
15
+ The rule matches on method names, so it covers Jest, Vitest and Bun alike.
16
+
17
+ ## What it flags
18
+
19
+ `expect(...)`, or `obj.expect(...)` on an identifier (`t.expect`, `chai.expect`), whose path up to
20
+ the enclosing test or suite callback crosses the conditional part of a branch. The test of an `if`
21
+ and the left side of a logical expression run unconditionally and are not flagged.
22
+
23
+ The search stops at the enclosing `it` / `test` / `describe` / `suite` callback, so a suite-level
24
+ loop or `if` that generates tests does not flag the expects inside those tests.
25
+
26
+ A test that calls `expect.assertions(n)` or `expect.hasAssertions()` is exempt: a skipped branch
27
+ already fails it.
28
+
29
+ ```ts
30
+ // Bad
31
+ it('rejects bad input', async () => {
32
+ try {
33
+ await parse('');
34
+ } catch (error) {
35
+ expect(error).toBeInstanceOf(ParseError);
36
+ }
37
+ });
38
+
39
+ it('returns the value', () => {
40
+ const result = load();
41
+ if (result.ok) {
42
+ expect(result.value).toBe(1);
43
+ }
44
+ });
45
+ ```
46
+
47
+ ```ts
48
+ // Good
49
+ it('rejects bad input', async () => {
50
+ await expect(parse('')).rejects.toBeInstanceOf(ParseError);
51
+ });
52
+
53
+ it('returns the value', () => {
54
+ expect(load()).toEqual({ ok: true, value: 1 });
55
+ });
56
+
57
+ describe('parse', () => {
58
+ for (const c of cases) {
59
+ it(c.name, () => {
60
+ expect(parse(c.input)).toEqual(c.output);
61
+ });
62
+ }
63
+ });
64
+ ```
65
+
66
+ ## Options
67
+
68
+ | Option | Type | Default | Meaning |
69
+ | --- | --- | --- | --- |
70
+ | `checkLoops` | `boolean` | `false` | Also treat a `for` / `for...in` / `for...of` / `while` / `do...while` body as conditional, since a loop over an empty collection asserts nothing. |
71
+
72
+ `checkLoops` is off by default, unlike the tsforge original. On a real 650-file suite, loops made up
73
+ 164 of 173 reports, almost all table-driven loops over literal arrays and constant maps.
74
+
75
+ ```js
76
+ 'noctcore-code-quality/no-conditional-expect': ['error', { checkLoops: true }]
77
+ ```
78
+
79
+ ## When not to use it
80
+
81
+ If your suites rely on type-narrowing guards such as `if (result.success) expect(result.data)...`
82
+ after an unconditional `expect(result.success).toBe(true)`, and you do not want to rewrite them.
@@ -0,0 +1,75 @@
1
+ # `noctcore-code-quality/no-real-network-in-unit-tests`
2
+
3
+ > Unit tests must not perform real network I/O.
4
+
5
+ Ported from [tsforge](https://github.com/boringstack-xyz/tsforge) (MIT). See
6
+ [THIRD_PARTY_NOTICES.md](../../THIRD_PARTY_NOTICES.md).
7
+
8
+ ## Why
9
+
10
+ A unit test that calls `fetch` or `axios` for real depends on a server, a port, DNS and the network
11
+ being up. It is slow, flaky and order-dependent, and it hides the fact that the code under test has
12
+ no seam for a test double. Mock the client, or move the test to an integration suite where real I/O
13
+ is the point.
14
+
15
+ ## What it flags
16
+
17
+ In a unit test file (a path ending in one of `testFileSuffixes`, and not containing any
18
+ `integrationMarkers`):
19
+
20
+ - a call to a `networkCallees` global: `fetch(...)`, `globalThis.fetch(...)`, `window.fetch(...)`;
21
+ - a call to an `httpClients` client or its request methods: `axios(...)`, `axios.get(...)`,
22
+ `axios.post(...)`, and `put` / `patch` / `delete` / `head` / `options` / `request`.
23
+
24
+ It does not flag:
25
+
26
+ - a locally declared double (`const fetch = vi.fn()`); an imported `fetch` is still reported;
27
+ - a global the file stubs (`vi.stubGlobal('fetch', ...)`, `jest.spyOn(globalThis, 'fetch')`,
28
+ `globalThis.fetch = vi.fn()`);
29
+ - a client whose module the file mocks (`vi.mock('axios')`, `jest.mock('node-fetch')`);
30
+ - a method that only shares a name (`repository.fetch(1)`, `store.get('k')`).
31
+
32
+ ```ts
33
+ // Bad: src/api/client.test.ts
34
+ it('loads the profile', async () => {
35
+ const res = await fetch('https://api.example.com/me');
36
+ expect(res.status).toBe(200);
37
+ });
38
+ ```
39
+
40
+ ```ts
41
+ // Good: src/api/client.test.ts
42
+ it('loads the profile', async () => {
43
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response('{"id":1}')));
44
+ expect(await loadProfile()).toEqual({ id: 1 });
45
+ });
46
+
47
+ // Good: src/api/client.integration.test.ts runs against a real server.
48
+ ```
49
+
50
+ ## Options
51
+
52
+ | Option | Type | Default | Meaning |
53
+ | --- | --- | --- | --- |
54
+ | `testFileSuffixes` | `string[]` | `.test` / `.spec` with `.ts`, `.tsx`, `.js`, `.jsx` | A file is a unit test when its path ends with one of these. |
55
+ | `integrationMarkers` | `string[]` | `.integration.test.`, `.integration.spec.`, `.e2e.test.`, `.e2e.spec.`, `.e2e-spec.`, `/integration/`, `/e2e/` | A test file whose path, relative to the ESLint working directory, contains one of these is skipped. |
56
+ | `networkCallees` | `string[]` | `["fetch"]` | Global functions that perform network I/O. |
57
+ | `httpClients` | `string[]` | `["axios"]` | HTTP clients whose direct call or request methods perform network I/O. |
58
+
59
+ ```js
60
+ 'noctcore-code-quality/no-real-network-in-unit-tests': ['error', {
61
+ integrationMarkers: ['.integration.', '/e2e/', '.live.'],
62
+ httpClients: ['axios', 'ky'],
63
+ }]
64
+ ```
65
+
66
+ ## Limitations
67
+
68
+ The rule sees calls in the test file only, not network calls made by the code under test. A request
69
+ intercepted by a setup-file mock server (for example MSW) is still reported when the test file itself
70
+ calls `fetch`; add that file's suffix to `integrationMarkers` or disable the rule for it.
71
+
72
+ ## When not to use it
73
+
74
+ If your unit tests deliberately run against a local server started in-process, name those files with
75
+ an integration marker instead of turning the rule off.
@@ -0,0 +1,89 @@
1
+ # `noctcore-code-quality/no-vacuous-expect`
2
+
3
+ > A test must assert behaviour that a real regression would break.
4
+
5
+ Ported from [tsforge](https://github.com/boringstack-xyz/tsforge) (MIT). See
6
+ [THIRD_PARTY_NOTICES.md](../../THIRD_PARTY_NOTICES.md).
7
+
8
+ ## Why
9
+
10
+ Some assertions pass for almost any implementation. `expect(typeof handler).toBe('function')` proves
11
+ a binding exists. `expect(true).toBe(true)` cannot fail. A test whose only assertion is
12
+ `toBeDefined()` or `toBeTruthy()` stays green when the function returns the wrong object, the wrong
13
+ string or the wrong number. These tests add to the count and protect nothing.
14
+
15
+ The rule matches on method names, not on a runner import, so it covers Jest, Vitest and Bun alike.
16
+
17
+ ## What it flags
18
+
19
+ - `typeofExpect`: `expect(typeof x).toBe('<typeof result>')`, also with `toEqual`, `toStrictEqual`
20
+ and `.not`.
21
+ - `tautologyExpect`: `expect(<literal>).toBe(<same literal>)`, also with `toEqual` / `toStrictEqual`.
22
+ - `soleWeakExpect`: a test (`it` / `test`, including `.concurrent`, `.each` and other modifiers)
23
+ whose only assertion is a weak matcher.
24
+
25
+ A test counts every `expect(...)` matcher plus any call matching `assertionCallees`, so a weak
26
+ `expect` next to `assert.equal(...)`, `expectValidUser(...)` or supertest's `.expect(200)` is fine.
27
+
28
+ ```ts
29
+ // Bad
30
+ it('should be defined', () => {
31
+ expect(service).toBeDefined();
32
+ });
33
+
34
+ it('returns a token', () => {
35
+ expect(typeof issueToken()).toBe('string');
36
+ });
37
+
38
+ it('works', () => {
39
+ expect(true).toBe(true);
40
+ });
41
+ ```
42
+
43
+ ```ts
44
+ // Good
45
+ it('issues a signed token for the user', () => {
46
+ const token = issueToken({ userId: 'u-1' });
47
+ expect(verify(token)).toEqual({ userId: 'u-1' });
48
+ });
49
+
50
+ it('creates the user', () => {
51
+ const user = create({ name: 'ada' });
52
+ expect(user).toBeDefined();
53
+ expect(user.name).toBe('ada');
54
+ });
55
+
56
+ it('clears the key', () => {
57
+ cache.delete('k');
58
+ expect(cache.get('k')).toBeUndefined(); // a specific absence, not a weak check
59
+ });
60
+ ```
61
+
62
+ ## Options
63
+
64
+ | Option | Type | Default | Meaning |
65
+ | --- | --- | --- | --- |
66
+ | `weakMatchers` | `string[]` | `["toBeDefined", "toBeTruthy", "toBeFalsy", "not.toBeUndefined"]` | Matchers that cannot carry a test alone. Prefix `not.` for the negated form. |
67
+ | `assertionCallees` | `string[]` (regex sources) | `["^assert", "^expect\\w", "\\.expect$"]` | Calls that also count as an assertion. Matched against `name`, `obj.name` (member on an identifier) or `.name` (any other member). |
68
+
69
+ `toBeUndefined`, `toBeNull` and `not.toBeNull` are not weak by default: each pins one specific
70
+ value, and `expect(container.querySelector('nav')).not.toBeNull()` is a real presence check.
71
+
72
+ ```js
73
+ // Treat toBeUndefined as weak too, and count a project helper as an assertion.
74
+ 'noctcore-code-quality/no-vacuous-expect': ['error', {
75
+ weakMatchers: ['toBeDefined', 'toBeTruthy', 'toBeFalsy', 'toBeUndefined'],
76
+ assertionCallees: ['^assert', '^expect\\w', '\\.expect$', '^verifySnapshot$'],
77
+ }]
78
+ ```
79
+
80
+ ## Limitations
81
+
82
+ Assertions are counted syntactically inside the test callback. An assertion hidden in a helper whose
83
+ name does not match `assertionCallees` is not seen. A sole `toBeTruthy()` on a Testing Library
84
+ `getBy*` query is reported even though the query itself throws when the element is missing; assert
85
+ with a matcher that states the intent instead.
86
+
87
+ ## When not to use it
88
+
89
+ In a smoke suite whose only purpose is to prove modules load.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@noctcore/eslint-plugin-code-quality",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Portable code-quality, comment-hygiene, and test-discipline ESLint rules.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -18,7 +18,8 @@
18
18
  "files": [
19
19
  "dist",
20
20
  "docs",
21
- "README.md"
21
+ "README.md",
22
+ "THIRD_PARTY_NOTICES.md"
22
23
  ],
23
24
  "sideEffects": false,
24
25
  "keywords": [
@@ -59,6 +60,6 @@
59
60
  "@typescript-eslint/rule-tester": "^8.61.1",
60
61
  "tsup": "^8.5.1",
61
62
  "typescript": "^5.6.0",
62
- "vitest": "^3"
63
+ "vitest": "^4"
63
64
  }
64
65
  }