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

James
James

Posted on

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

Top comments (0)

typescript

11 Tips That Make You a Better Typescript Programmer

1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields

...

Read the whole post now!