我创建了一个 HOC 来验证用户是否已通过身份验证并在需要时对用户进行身份验证,这非常有效......直到测试为止。
我移动了索引中的所有导入,因为我看到可能存在提升问题。在我的 src/services/index.ts
export * from './RequireAuth'
export * from './ToasterContext'
RequireAuth 代码:
import { useEffect, ComponentType, useState, useContext, Fragment } from 'react'
import { useHistory, useLocation } from 'react-router'
import { UserContext } from '../services'
interface WrappedComponentProps {
[key: string]: any //eslint-disable-line
}
export function RequireAuth<P extends WrappedComponentProps>(
WrappedComponent: ComponentType<P>
) {
return function Comp(props: P) {
const [hasGroup, setHasGroup] = useState<boolean>()
const { authUser } = useContext(UserContext)
const history = useHistory()
const location = useLocation()
useEffect(() => {
if (!authUser) {
history.push('/login')
} else {
// do something
}
}, [authUser, hasGroup])
const isAuthorized = authUser && hasGroup
if (!isAuthorized) {
return <Fragment></Fragment> //TODO
}
return <WrappedComponent {...(props as P)} />
}
}
令人惊讶的是,我尝试测试的组件与 RequireAuth HOC 无关。
被测试的组件:
import { ToasterProvider } from './../services'
import { act, render } from '@testing-library/react'
test('Render the component', () => {
provider = render(
<ToasterProvider>
<div />
</ToasterProvider>
)
expect(provider.container.getElementsByClassName('p-toast').length).toBe(1)
})