【问题标题】:Mocking react custom hook模拟反应自定义钩子
【发布时间】:2021-04-06 17:54:33
【问题描述】:

我需要模拟 useLogin 钩子,因为它包含引发错误的逻辑。稍后我将单独测试它。 UseLogin 返回将新用户连接到firebase的加载标志和登录函数。

import useLogin from "../../../hooks/useLogin";

export default function Login({ register, handleSubmit }) {
  const [loading, login] = useLogin();

  return (
    <Form onSubmit={handleSubmit(login)}>
    {...other components}
    <Form>
  );
}

使用登录挂钩

import { useState } from "react";
import { useHistory } from "react-router";
import { useModalContext } from "../../context";

import { firebase } from "../../libs/firebase";

export default function useLogin() {
  const [loading, setLoading] = useState(false);
  const [, { showErrorModal }] = useModalContext();
  const history = useHistory();

  function login({ email, password }) {
    setLoading(true);
    firebase
      .auth()
      .signInWithEmailAndPassword(email, password)
      .then(() => {
        setLoading(false);
        history.push("/");
      })
      .catch(() => {
        setLoading(false);
        showErrorModal("User not found");
      });
  }

  return [loading, login];
}

【问题讨论】:

    标签: javascript reactjs jestjs react-testing-library


    【解决方案1】:

    您应该尽可能避免模拟自己的组件,因为如果您更改组件代码,您将需要同时维护组件和模拟。您仍然可以对此进行测试并测试隔离的useLogin 挂钩,以测试所有不同的代码分支等等。

    当去外面的世界发出 API 请求时,建议使用一个库,该库允许您在不打扰的情况下模拟它们。像 nock 或 Mock Service Worker 这样的库可以让你做到这一点,这样你就可以avoid mocking fetch。

    也就是说,如果您需要模拟它,您可以模拟 firebase 库以返回所需的任何内容。您可以使用常规的 Jest 模拟来做到这一点,或者试试这个 firebase-mock 库,以防您需要模拟更多的 firebase 功能和 here you can see how it integrates with Jest。

    创建您自己的自定义模拟可能是更快的选择,如果您不需要模拟其他任何东西,它也可能是最佳选择。在这里您可以看到一个自定义 Firebase 模拟的示例:Mock implementation of firebase auth methods after mocking the firebase module

    【讨论】:

    • 谢谢你,对我很有帮助的建议:3
    猜你喜欢
    • 2020-06-01
    • 1970-01-01
    • 2019-06-15
    • 2022-07-18
    • 1970-01-01
    • 2021-09-29
    • 2020-03-08
    • 1970-01-01
    • 2020-07-07
    相关资源
    最近更新 更多