遵循这篇博文中解释的 Kent C Dodds 的提供者模式,我有一个上下文提供者组件以及一个使用该上下文的钩子。
钩子防止在提供者之外使用它,
export function useUser() {
const { user } = useContext(UserContext) || {};
const { switchUser } = useContext(SwitchUserContext) || {};
if (!user || !switchUser) {
throw new Error('Cannot use `useUser` outside of `UserProvider`');
}
return { user, switchUser };
}
Run Code Online (Sandbox Code Playgroud)
为了测试场景,我创建了一个TestComponent并在其中使用了useUser钩子。
function TestComponent() {
const { user, switchUser } = useUser();
return (
<>
<p>User: {user.name}</p>
<button onClick={switchUser}>Switch user</button>
</>
);
}
Run Code Online (Sandbox Code Playgroud)
我是这样测试的
test('should throw error when not …Run Code Online (Sandbox Code Playgroud)