DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Cover image for One React testing tip
Bruno Noriller
Bruno Noriller

Posted on • Originally published at linkedin.com

One React testing tip

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>
    )
}
Enter fullscreen mode Exit fullscreen mode

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>
    )
}
Enter fullscreen mode Exit fullscreen mode

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 */} />
)
Enter fullscreen mode Exit fullscreen mode

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>
    )
}
Enter fullscreen mode Exit fullscreen mode

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)

Here is a post you might want to check out:

Regex for lazy developers

regex for lazy devs

Sorry for the callout πŸ˜†