We have a Next.js app that uses the react-oidc-context Node module, as we are using ADFS for authentication.
Currently, I am trying to write unit tests using Vitest, and am getting this error:
TypeError: Cannot read properties of undefined (reading 'isAuthenticated')
Which comes from this in our index.jsx page:
if (!auth.isAuthenticated) {
// return "loading" page
}
return (
// return "working" page
);
Tracing that back, it comes from this custom hook we wrote:
const auth = useOidcAuth();
Which comes from this import:
import { useAuth as useOidcAuth } from "react-oidc-context";
Which comes from this export in react-oidc-context.d.ts:
export declare const useAuth: () => AuthContextProps;
Which comes from this interface in react-oidc-context.d.ts:
export declare interface AuthContextProps extends AuthState {
// ...
}
Which comes from this interface in react-oidc-context.d.ts:
export declare interface AuthState {
/**
* See [User](https://authts.github.io/oidc-client-ts/classes/User.html) for more details.
*/
user?: User | null;
/**
* True when the library has been initialized and no navigator request is in progress.
*/
isLoading: boolean;
/**
* True while the user has a valid access token.
*/
isAuthenticated: boolean;
/**
* Tracks the status of most recent signin/signout request method.
*/
activeNavigator?:
| "signinRedirect"
| "signinPopup"
| "signinSilent"
| "signoutRedirect"
| "signoutPopup"
| "signoutSilent";
/**
* Was there a signin or silent renew error?
*/
error?: Error;
}
I need to mock or implement that AuthState interface so I can "fake" an authenticated log-in to proceed with testing.
Is this possible, and how would I go about doing this?
vi.mock() is used for mocking modules, functions, or objects during tests, allowing you to control their behavior and simulate different scenarios.
import { it, vi } from 'vitest';
import { useAuth as useOidcAuth } from 'react-oidc-context';
vi.mock('react-oidc-context', () => {
return {
// It doesn't matter if you renamed it to useOidcAuth upon import, the original one needs to be mocked.
useAuth: () => ({
isLoading: false,
isAuthenticated: true,
}),
};
});
it('user is authenticated', () => {
const auth = useOidcAuth();
expect(auth.isAuthenticated).toBeTruthy();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With