react-oidc-context
react-oidc-context copied to clipboard
Unable to mock useAuth with jest
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.
With auth.useAuth.mockResolvedValue('test'); you mock useAuth like it would be a string ("test"), but it is a function...
@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...
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