DEV Community

James
James

Posted on

2 1

Mocking components in Jest

Mocking React components and modules is something I find myself doing often in Jest. I’m instinctively weary of mocks, test doubles can create a false sense of security if misused, but they are incredibly important when dealing with third party libraries and "Inner-Source" packages, whilst avoiding the indirection and complexity of other techniques such as Dependency Injection. I don’t personally believe that mocking/patching in anyway compromises a clean architecture.

Below is a common mock in the codebase I'm working on. Next.js links will fail with an TypeError without a RouterContext. Either we add the router or mock the component, the latter seems easiest and prevents the test from knowing too much about what's needed underneath.

jest.mock('next/link', () => ({ children }: { children: JSX.Element }) => children); 
Enter fullscreen mode Exit fullscreen mode

Of course that'll work on any component import.

Unfortunately if you want to return some JSX in the mock the react/display-name ESlint rule will kick in. We can ignore the rule or perhaps define the mock like this:

jest.mock('../module', () => function Named() { return <div />; });
Enter fullscreen mode Exit fullscreen mode

Oh, and named exports? The above examples show default exports. The example below takes Stripe's CardElement and return a no-op component.

jest.mock('@stripe/react-stripe-js', () => ({ CardElement: () => null }));
Enter fullscreen mode Exit fullscreen mode

Image of Datadog

How to Diagram Your Cloud Architecture

Cloud architecture diagrams provide critical visibility into the resources in your environment and how they’re connected. In our latest eBook, AWS Solution Architects Jason Mimick and James Wenzel walk through best practices on how to build effective and professional diagrams.

Download the Free eBook

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay