How to test a react component that is dependent on useContext hook?

Posted by Jessica Taylor | Updated on

If you want to test a react component that is dependent on useContext hook? In general, using hooks shouldn’t change testing strategy much. The bigger issue here actually isn’t the hook, but the use of context, which complicates things a bit.

There’s a number of ways to make this work, but only approach I’ve found that works with ‘react-test-renderer/shallow’ is to inject a mock hook:

Reference:
https://stackoverflow.com/questions/54691799/how-to-test-a-react-component-that-is-dependent-on-usecontext-hook


If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.

Related Questions & Answers