UNPKG

eslint-plugin-no-multiple-returns

Version:

An ESLint plugin to enforce a single `return` statement per function, encouraging clearer and more maintainable code.

81 lines (75 loc) 2.83 kB
import { describe, it } from "vitest"; import { RuleTester } from "eslint"; import rule from "../src/rules/no-multiple-returns"; // ESLint RuleTester needs to be configured properly for Vitest const ruleTester = new RuleTester({ languageOptions: { ecmaVersion: 2020, sourceType: "module", }, }); describe("no-multiple-returns", () => { it("should validate the rule", () => { ruleTester.run("no-multiple-returns", rule, { valid: [ `function singleReturn() { return 1; }`, `const fn = () => { return 42; }`, `const concise = () => 123;`, // Test case: nested function with return should not count as multiple returns `const TimerComponent = () => { const [seconds, setSeconds] = useState(0); useEffect(() => { const intervalId = setInterval(() => { setSeconds((prev) => prev + 1); }, 1000); return () => { clearInterval(intervalId); console.log('Timer cleaned up'); }; }, []); return React.createElement('div', null, 'Timer: ' + seconds + 's'); };`, // Test case: nested React component should not count as multiple returns `const ParentComponent = () => { const NestedComponent = () => { return React.createElement('span', null, 'Nested'); }; return React.createElement('div', null, React.createElement(NestedComponent, null)); };`, // Test case: function with conditional returns inside React component (should be valid) `const ConditionalComponent = () => { const helper = (condition) => { if (condition) return 'yes'; return 'no'; }; return React.createElement('div', null, helper(true)); };`, // Test case: complex nested scenario with useEffect and nested components `const ComplexComponent = () => { const [state, setState] = useState(false); useEffect(() => { const cleanup = () => { if (state) return 'cleanup1'; return 'cleanup2'; }; return cleanup; }, [state]); const NestedComp = () => { return React.createElement('span', null, 'nested'); }; return React.createElement('div', null, React.createElement(NestedComp, null)); };`, ], invalid: [ { code: `function bad() { if (x) return 1; return 2; }`, errors: [{ message: /has 2 return statements/ }], }, { code: `const bad = () => { if (x) return 1; return 2; };`, errors: [{ message: /has 2 return statements/ }], }, ], }); }); });