Reputation: 13
I'm trying to write a unit test for a Card compenent using Jest. This component takes a framer-motion value and a ref as Props. This values can only be created using the useMotionValue and useRef hook.
interface Props {
currentIndex: MotionValue<number>;
containerRef: RefObject<HTMLDivElement>;
}
Currently, I'm able to pass in a dummy value for the ref using document.createElement
, but when i tried creating a motion value to pass into the component, I get an error saying that react hooks cannot be used ouside a component
it("renders a card", () => {
const container = document.createElement("div");
render(
<Card
containerRef={{ current: container }}
currentIndex={******} // motion value goes here
/>
);
});
I had to render the component in a parent component first and then test the parent Component but i was wondering, is there a way to mock the motion value and pass it in as a prop?
Upvotes: 0
Views: 1264
Reputation: 1237
The easiest way would be to mock useMotionValue
implementation. You can use jest.mock
at the top of your file where you write your test for the component that uses this hook. Remember also to not mock other functionality by requiring actual implementation.
// at the top of the file that tests component with useMotionValue call
jest.mock('framer-motion', () => ({
...jest.requireActual('framer-motion'),
useMotionValue: jest.fn().mockReturnValue({
// put here the mock implementation of MotionValue methods
})
}));
Upvotes: 0