小编Bha*_*hah的帖子

使用 testing-library 和 jest 测试 React 组件抛出的错误

遵循这篇文中解释的 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)

reactjs jestjs react-context react-testing-library

4
推荐指数
1
解决办法
2313
查看次数