October 31, 2019
How to Spy on a React Prop with Jest
When we want to test whether a prop has been called, mocking the prop in the component is usually the preferred way. This is how it goes with Jest and Enzyme:
const buy = jest.fn();
const wrapper = enzyme.shallow(<button onClick={buy}>Buy</button>);
wrapper.simulate("click");
expect(buy).toBeCalled();
You may also want to spy on the prop directly, when the component is tested along with a provider passing down its props.
const wrapper = enzyme.shallow(
<ClickProvider>
<button>Buy</button>
</ClickProvider>
);
const buy = jest.spyOn(wrapper.instance().props, "onClick");
wrapper.simulate("click");
expect(buy).toBeCalled();
I am using Enzyme however you should be able to spy on similarly using other testing libraries – just make sure you are spying on a function in the props coming from the component prototype (as in wrapper.instance()
).
That’s all. Just posting it here cuz I couldn’t find it easily anywhere else.