react-oidc-context icon indicating copy to clipboard operation
react-oidc-context copied to clipboard

Unable to mock useAuth with jest

Open raghavi92 opened this issue 1 year ago • 3 comments

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.

raghavi92 avatar Jun 24 '24 06:06 raghavi92

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

pamapa avatar Jun 24 '24 09:06 pamapa

@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...

raghavi92 avatar Jun 26 '24 06:06 raghavi92

I was able to mock like this

import '@testing-library/jest-dom'
import { vi } from 'vitest'
import { userMock } from './mocks/user'

const mockAuthenticatedStatus = {
  isLoading: false,
  isAuthenticated: true,
}

const getMockAuthStatus = () => {
  return mockAuthenticatedStatus
}

vi.mock('react-oidc-context', () => ({
  useAuth() {
    const { isLoading, isAuthenticated } = getMockAuthStatus()
    return {
      isLoading,
      isAuthenticated,
      signinRedirect: vi.fn(),
      removeUser: vi.fn(),
      settings: {},
      user: userMock,
    }
  },
  hasAuthParams: vi.fn(() => true),
}))

Thanks to this answer in stackoverflow: https://stackoverflow.com/a/77403193

Rafael-Ramblas avatar Mar 18 '25 18:03 Rafael-Ramblas