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?
useAuthhook like described in this other SO question: stackoverflow.com/q/60270013/8583669? You could just return the object{ isAuthenticated: true }.