authts / react-oidc-context

Lightweight auth library based on oidc-client-ts for React single page applications (SPA). Support for hooks and higher-order components (HOC).
MIT License
669 stars 65 forks source link

Unable to mock useAuth with jest #1290

Open raghavi92 opened 3 months ago

raghavi92 commented 3 months ago

I went through this already existing issue: https://github.com/authts/react-oidc-context/issues/372

But my mock for the useAuth function is simply not working. Can someone help please ?

I added the below code segment to my test file:

const auth = require('react-oidc-context');
jest.mock('react-oidc-context', () => {
  const orig = jest.requireActual('react-oidc-context');
  return {
    __esModule: true,
    default: jest.fn(),
    useAuth: jest.fn(),
    ...orig,
  };
});
  auth.useAuth.mockResolvedValue('test');
  render(<App />, {
    wrapper: ({ children }) => (
      <AuthProvider
        authority='authority'
        client_id='client'
        redirect_uri='redirect'
      >
        {children}
      </AuthProvider>
    ),
  });

  waitFor(() => {
    expect(
      screen.getByText('Tournaments managed by Lotus Chess Academy')
    ).toBeInTheDocument();
  });
});

I'm getting the error TypeError: auth.useAuth.mockResolvedValue is not a function. I have a nextjs project with typescript enabled.

pamapa commented 3 months ago

With auth.useAuth.mockResolvedValue('test'); you mock useAuth like it would be a string ("test"), but it is a function...

raghavi92 commented 3 months ago

@pamapa Actually I tried this first but it didnt work:

jest.mock('react-oidc-context', () => {
  const orig = jest.requireActual('react-oidc-context');
  return {
    __esModule: true,
    default: jest.fn(),
    useAuth: jest.fn,
    ...orig,
  };
});

I might have pasted my last snippet out of a lot of failed attempts...