| 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 {render} from '@testing-library/react'; |
| 9 | import * as React from 'react'; |
| 10 | |
| 11 | function Button({label}) { |
| 12 | const theme = useTheme(); |
| 13 | const style = computeStyle(theme); |
| 14 | return <button color={style}>{label}</button>; |
| 15 | } |
| 16 | |
| 17 | let currentTheme = 'light'; |
| 18 | function useTheme() { |
| 19 | 'use memo'; |
| 20 | return currentTheme; |
| 21 | } |
| 22 | |
| 23 | let styleComputations = 0; |
| 24 | function computeStyle(theme) { |
| 25 | styleComputations++; |
| 26 | return theme === 'light' ? 'white' : 'black'; |
| 27 | } |
| 28 | |
| 29 | test('update-button', () => { |
| 30 | const {asFragment, rerender} = render(<Button label="Click me" />); |
| 31 | expect(asFragment()).toMatchInlineSnapshot(` |
| 32 | <DocumentFragment> |
| 33 | <button |
| 34 | color="white" |
| 35 | > |
| 36 | Click me |
| 37 | </button> |
| 38 | </DocumentFragment> |
| 39 | `); |
| 40 | |
| 41 | // Update the label, but not the theme |
| 42 | rerender(<Button label="Click again" />); |
| 43 | // `computeStyle` should not be called again when Forget is enabled |
| 44 | expect(styleComputations).toBe(__FORGET__ ? 1 : 2); |
| 45 | expect(asFragment()).toMatchInlineSnapshot(` |
| 46 | <DocumentFragment> |
| 47 | <button |
| 48 | color="white" |
| 49 | > |
| 50 | Click again |
| 51 | </button> |
| 52 | </DocumentFragment> |
| 53 | `); |
| 54 | |
| 55 | currentTheme = 'dark'; |
| 56 | rerender(<Button label="Click again" />); |
| 57 | expect(asFragment()).toMatchInlineSnapshot(` |
| 58 | <DocumentFragment> |
| 59 | <button |
| 60 | color="black" |
| 61 | > |
| 62 | Click again |
| 63 | </button> |
| 64 | </DocumentFragment> |
| 65 | `); |
| 66 | |
| 67 | expect(styleComputations).toBe(__FORGET__ ? 2 : 3); |
| 68 | }); |