Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

react-effect-budget.test.ts

60 lines2.1 KB

1import { assert, describe } from "@effect/vitest";
2​
3import budget from "../../scripts/effect-budget.json" with { type: "json" };
4import { createOxlintRuleHarness } from "../test/utils.ts";
5​
6const [budgetedFile, allowed] = Object.entries(budget)[0]!;
7​
8const component = (effects: number) => `import React, { useEffect } from "react";
9export function Panel() {
10${Array.from({ length: effects }, (_, index) => (index % 2 === 0 ? " useEffect(() => {}, []);" : " React.useLayoutEffect(() => {});")).join("\n")}
11 return null;
13`;
14​
15const reports = (output: string) => output.match(/t3code\(react-effect-budget\)/g)?.length ?? 0;
16const lint = (filename: string) =>
17 createOxlintRuleHarness("t3code/react-effect-budget", { filename });
18​
19const budgeted = lint(budgetedFile);
20const unbudgeted = lint("apps/web/src/NotInTheBudget.tsx");
21​
22describe("t3code/react-effect-budget", () => {
23 budgeted.valid("passes a file at its budget", component(allowed));
24​
25 budgeted.invalid("reports only the calls past the budget", component(allowed + 2), (output) => {
26 assert.strictEqual(reports(output), 2);
27 assert.include(output, `has ${allowed + 2} React effects against a budget of ${allowed}`);
28 });
29​
30 unbudgeted.invalid(
31 "gives a file without an entry a budget of 0, counting member calls",
32 `export function New() { React.useEffect(() => {}); return null; }`,
33 (output) => {
34 assert.strictEqual(reports(output), 1);
35 assert.include(output, "has 1 React effect against a budget of 0");
36 },
37 );
38​
39 unbudgeted.valid(
40 "ignores comments, strings and lookalike names",
41 `// useEffect(() => {}) in a comment
42/* React.useLayoutEffect(() => {}) */
43const label = "useEffect(() => {})";
44const pipeline = Effect.matchCauseEffect(effect, {});
45const alias = useEffect;
46`,
47 );
48​
49 unbudgeted.valid(
50 "does not count an effect that states its reason",
51 `export function New() {
52 // oxlint-disable-next-line t3code/react-effect-budget -- subscribes to the window's resize events
53 React.useEffect(() => {});
54 return null;
56`,
57 );
58​
59 lint("apps/web/src/Panel.test.tsx").valid("skips test files", component(3));
60});