DEV Community

Srikanth Kyatham
Srikanth Kyatham

Posted on • Edited on

Mock React hooks based on environment

Hi

Recently I had an issue that there exists on React hook which was available only in the production environment since our application is being loaded inside other framework, which provided it.

Basic issue is you cannot place the hook inside a condition.

I needed to mock the hook, I have searched on the web and found hook mocking using jest.

Hence the following approach.

Let says my hook is useServerData very unintuitive. But for this purpose its fine.

I have created a mock hook, useServerDataMock in my mock file.

useServerData would given an object

{
  userId: string,
  meta: any
}
Enter fullscreen mode Exit fullscreen mode

In my mock.ts

const useServerDataMock = () => {
  return {
    userId: "testId",
    meta: {}
  }
}
Enter fullscreen mode Exit fullscreen mode

Now how to use mock hook based on Dev or Prod environment

interface ContainerProps {
  serverData: ServerData
}
const Container = (props: ContainerProps) => {
  ..
}
const ProdContainer = () => {
  const serverData = useServerData()
  return <Container serverData={serverData} />
}
const DevContainer = () => {
  const serverData = useServerDataMock()
  return <Container serverData={serverData} />
}

const App = () => {
  if (process.env.NODE_ENV === "production") {
    return <ProdContainer />
  } else {
    return <DevContainer />
  }
}
Enter fullscreen mode Exit fullscreen mode

Hope this helps someone facing similar issue.

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)

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay