| 1 | /** |
| 2 | * Copyright (c) Meta Platforms, Inc. and affiliates. |
| 3 | * |
| 4 | * This source code is licensed under the MIT license found in the |
| 5 | * LICENSE file in the root directory of this source tree. |
| 6 | */ |
| 7 | |
| 8 | import { |
| 9 | ErrorCategory, |
| 10 | getRuleForCategory, |
| 11 | } from 'babel-plugin-react-compiler/src/CompilerError'; |
| 12 | import {normalizeIndent, makeTestCaseError, testRule} from './shared-utils'; |
| 13 | import {allRules} from '../src/rules/ReactCompilerRule'; |
| 14 | |
| 15 | testRule( |
| 16 | 'rules-of-hooks', |
| 17 | allRules[getRuleForCategory(ErrorCategory.Hooks).name].rule, |
| 18 | { |
| 19 | valid: [ |
| 20 | { |
| 21 | name: 'Basic example', |
| 22 | code: normalizeIndent` |
| 23 | function Component() { |
| 24 | useHook(); |
| 25 | return <div>Hello world</div>; |
| 26 | } |
| 27 | `, |
| 28 | }, |
| 29 | { |
| 30 | name: 'Violation with Flow suppression', |
| 31 | code: ` |
| 32 | // Valid since error already suppressed with flow. |
| 33 | function useHook() { |
| 34 | if (cond) { |
| 35 | // $FlowFixMe[react-rule-hook] |
| 36 | useConditionalHook(); |
| 37 | } |
| 38 | } |
| 39 | `, |
| 40 | }, |
| 41 | { |
| 42 | // OK because invariants are only meant for the compiler team's consumption |
| 43 | name: '[Invariant] Defined after use', |
| 44 | code: normalizeIndent` |
| 45 | function Component(props) { |
| 46 | let y = function () { |
| 47 | m(x); |
| 48 | }; |
| 49 | |
| 50 | let x = { a }; |
| 51 | m(x); |
| 52 | return y; |
| 53 | } |
| 54 | `, |
| 55 | }, |
| 56 | { |
| 57 | name: "Classes don't throw", |
| 58 | code: normalizeIndent` |
| 59 | class Foo { |
| 60 | #bar() {} |
| 61 | } |
| 62 | `, |
| 63 | }, |
| 64 | ], |
| 65 | invalid: [ |
| 66 | { |
| 67 | name: 'Simple violation', |
| 68 | code: normalizeIndent` |
| 69 | function useConditional() { |
| 70 | if (cond) { |
| 71 | useConditionalHook(); |
| 72 | } |
| 73 | } |
| 74 | `, |
| 75 | errors: [ |
| 76 | makeTestCaseError( |
| 77 | 'Hooks must always be called in a consistent order', |
| 78 | ), |
| 79 | ], |
| 80 | }, |
| 81 | { |
| 82 | name: 'Multiple diagnostics within the same function are surfaced', |
| 83 | code: normalizeIndent` |
| 84 | function useConditional() { |
| 85 | cond ?? useConditionalHook(); |
| 86 | props.cond && useConditionalHook(); |
| 87 | return <div>Hello world</div>; |
| 88 | }`, |
| 89 | errors: [ |
| 90 | makeTestCaseError( |
| 91 | 'Hooks must always be called in a consistent order', |
| 92 | ), |
| 93 | makeTestCaseError( |
| 94 | 'Hooks must always be called in a consistent order', |
| 95 | ), |
| 96 | ], |
| 97 | }, |
| 98 | ], |
| 99 | }, |
| 100 | ); |