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.

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

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

Okay