我们有一个使用react-oidc-context Node模块的Next.js应用程序,因为我们使用ADFS进行身份验证。
目前,我正在尝试使用 Vitest 编写单元测试,并收到此错误:
TypeError: Cannot read properties of undefined (reading 'isAuthenticated')
这来自我们的
index.jsx
页面:
if (!auth.isAuthenticated) {
// return "loading" page
}
return (
// return "working" page
);
追溯起来,它来自我们编写的这个自定义钩子:
const auth = useOidcAuth();
来自此进口:
import { useAuth as useOidcAuth } from "react-oidc-context";
来自
react-oidc-context.d.ts
的出口:
export declare const useAuth: () => AuthContextProps;
来自
react-oidc-context.d.ts
中的这个界面:
export declare interface AuthContextProps extends AuthState {
// ...
}
来自
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;
}
我需要模拟或实现该
AuthState
接口,以便我可以“伪造”经过身份验证的登录来继续测试。
这可能吗?我该怎么做?
import { vi } from 'vitest';
import { useAuth } from 'react-oidc-context';
vi.mock('react-oidc-context', () => {
return {
useAuth: () => {
isLoading: false,
isAuthenticated: true,
},
};
});
it('user is authenticated', () => {
const auth = useAuth();
expect(auth.isAuthenticated).toBeTruthy();
});