import { describe, expect, it } from "bun:test"; import { hasReturnStatement, stripCommentsAndStrings, lintJavaScriptCode } from "./lint-js.js"; /** * return 检测曾经只跳过整行注释,行尾注释、块注释内部行和字符串里的 "return" * 都会让 missing-return 告警彻底失效。以下用例固定住这一修复。 */ describe("JavaScript return detection", () => { it("finds real return statements", () => { expect(hasReturnStatement("return a + b;")).toBe(true); expect(hasReturnStatement("const x = 1;\nif (x) { return x; }\nreturn 0;")).toBe(true); }); it("ignores returns in trailing comments", () => { expect(hasReturnStatement("const total = sum;\n// 记得 return 结果给下游")).toBe(false); }); it("ignores returns inside block comments", () => { expect(hasReturnStatement("/*\nreturn 1;\n*/\nprepare();")).toBe(false); expect(hasReturnStatement("/* return 1 */ prepare();")).toBe(false); }); it("ignores returns inside string literals", () => { expect(hasReturnStatement('log("return value: ");')).toBe(false); expect(hasReturnStatement("log('return value');")).toBe(false); expect(hasReturnStatement("log(`return ${x}`);")).toBe(false); }); it("does not treat identifiers containing return as a return", () => { expect(hasReturnStatement("returnValue = 1;")).toBe(false); expect(hasReturnStatement("const return_of_day = 3;")).toBe(false); }); it("still detects a return that follows commented-out code", () => { expect(hasReturnStatement("// return 1;\nreturn 2;")).toBe(true); }); }); describe("stripCommentsAndStrings", () => { it("keeps code characters and blanks out comment bodies", () => { expect(stripCommentsAndStrings("// c\nkeep")).toBe(`${" ".repeat(4)}\nkeep`); const blockStripped = stripCommentsAndStrings("/* x */ keep"); expect(blockStripped).toMatch(/^\s+keep$/); }); it("handles escaped quotes inside strings", () => { const stripped = stripCommentsAndStrings('"a\\"b" + x'); expect(stripped).not.toContain('"'); expect(stripped).toMatch(/\+\s*x$/); }); }); describe("lintJavaScriptCode missing-return reporting", () => { it("warns when only comments mention return", () => { const { issues } = lintJavaScriptCode("// 记得 return 值\nnormalize(data);"); expect(issues.map((i) => i.rule)).toContain("missing-return"); }); it("stays quiet when a real return exists", () => { const { issues, hasReturn } = lintJavaScriptCode("normalize(data);\nreturn data;"); expect(hasReturn).toBe(true); expect(issues.map((i) => i.rule)).not.toContain("missing-return"); }); });