|
| 1 | +import * as React from "react" |
| 2 | +import { motion } from "../.." |
| 3 | +import { render } from "../../jest.setup" |
| 4 | + |
| 5 | +/** |
| 6 | + * Regression test for #2777 |
| 7 | + * |
| 8 | + * When `motion.create()` wraps a custom component whose ref doesn't resolve to |
| 9 | + * a DOM element (e.g. the inner component is a class component, so its ref is |
| 10 | + * the class instance rather than a styleable element), the render loop would |
| 11 | + * throw `Cannot convert undefined or null to object` from deep inside the |
| 12 | + * frame loop, breaking every animation on the page. |
| 13 | + * |
| 14 | + * Motion should instead throw an actionable invariant at mount. |
| 15 | + */ |
| 16 | +describe("motion.create() wrapping a custom component with a non-DOM ref", () => { |
| 17 | + let consoleError: jest.SpyInstance |
| 18 | + |
| 19 | + beforeEach(() => { |
| 20 | + // React logs uncaught errors thrown from refs, which is noise here. |
| 21 | + consoleError = jest.spyOn(console, "error").mockImplementation(() => {}) |
| 22 | + }) |
| 23 | + |
| 24 | + afterEach(() => consoleError.mockRestore()) |
| 25 | + |
| 26 | + test("throws an actionable invariant when the ref isn't an element", () => { |
| 27 | + class ClassButton extends React.Component<any> { |
| 28 | + render() { |
| 29 | + return <button>{this.props.children}</button> |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + // Forwards the ref to a class component, so the mounted instance is the |
| 34 | + // class instance (no `.style`), mirroring the NextUI Button repro. |
| 35 | + const AnimateButton = React.forwardRef<any, any>((props, ref) => ( |
| 36 | + <ClassButton ref={ref} {...props} /> |
| 37 | + )) |
| 38 | + |
| 39 | + const MotionButton = motion.create(AnimateButton) |
| 40 | + |
| 41 | + expect(() => |
| 42 | + render(<MotionButton initial={{ opacity: 0 }}>BUY</MotionButton>) |
| 43 | + ).toThrowError( |
| 44 | + "motion.create() components must forward their ref to a HTML or SVG element. For more information and steps for solving, visit https://motion.dev/troubleshooting/custom-component-ref" |
| 45 | + ) |
| 46 | + }) |
| 47 | + |
| 48 | + test("mounts without error when the ref resolves to an element", () => { |
| 49 | + const AnimateButton = React.forwardRef<HTMLButtonElement, any>( |
| 50 | + (props, ref) => <button ref={ref} {...props} /> |
| 51 | + ) |
| 52 | + |
| 53 | + const MotionButton = motion.create(AnimateButton) |
| 54 | + |
| 55 | + expect(() => |
| 56 | + render(<MotionButton initial={{ opacity: 0 }}>BUY</MotionButton>) |
| 57 | + ).not.toThrow() |
| 58 | + }) |
| 59 | +}) |
0 commit comments