Use an API mocking library. Thatβs it, it will make your life easier, youβll be able to test everything without mocking basically anything and make Kent C. Dodds happy.
But we know that sometimes thatβs not possible...
Letβs say we have this:
// App.js
function App(){
return (
<ContextProvider>
<MainComponent />
</ContextProvider>
)
}
// Context stuff omitted
// MainComponent.js
function MainComponent(){
const contextValue = useContext();
return (
<div>
{contextValue}
</div>
)
}
You probably saw, made, and/or had to test something like this.
And it might be as easy as just wrapping your testing βrenderβ in the context provider or testing it indirectly, by never unit testing MainComponent
.
But what if you really want/need to unit test MainComponent
?
You certainly can think of a few ways to test it, but Iβll be offering one way that needs only a small refactor and that gives your unit testing superpowers.
// MainComponent.js
function MainComponent({
contextValue = useContext();
} = {}){
return (
<div>
{contextValue}
</div>
)
}
Thatβs it!
You just put the useContext as a default parameter in MainComponent
and in your tests you just:
render(
<MainComponent contextValue={/* anything you want */} />
)
This makes testing trivial. (and if the context fetch
something, then no mocking is required... yay!)
And if you have more levels of components above MainComponent
, then you can always mock MainComponent
:
// check your test framework, itβs pretty easy to do, just return something like:
const MockComponent = ({inputs, needed}) => {
return (
<div>
<div>{something}</div>
<div>{youWant}</div>
<div>{toCheck}</div>
</div>
)
}
But before using it, remember: if you can, first made the code easier to test!
If you canβt, or if youβre playing with untested legacy code... then: Tests are better than no tests.
Cover Photo by Girl with red hat on Unsplash
Top comments (0)