DEV Community

Srikanth Kyatham
Srikanth Kyatham

Posted on • Updated 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.

Top comments (0)