模拟反应自定义钩子
Mocking react custom hook
我需要模拟 useLogin 挂钩,因为它包含引发错误的逻辑。稍后我将单独测试它。 UseLogin returns 将新用户连接到 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];
}
您应该尽可能避免 mock 自己的组件,因为如果更改组件代码,您将需要同时维护组件和 mock。您仍然可以测试它并测试隔离的 useLogin
挂钩,以测试所有不同的代码分支等等。
在去往外部世界并发出 API 请求时,建议使用一个库,该库允许您在不打扰的情况下模拟它们。 nock or Mock Service Worker let you do exactly that, and this way you avoid mocking fetch.
这样的库
就是说,如果您需要对此进行模拟,您可以将 firebase 库模拟为 return 所需的任何内容。您可以使用常规的 Jest 模拟来完成,或者试试这个 firebase-mock library in case you will need to mock more of firebase features and here you can see how it integrates with Jest.
创建您自己的自定义模拟可能是更快的选择,如果您不需要模拟其他任何东西,它也可能是最好的选择。在这里您可以看到自定义 firebase 模拟的示例:
我需要模拟 useLogin 挂钩,因为它包含引发错误的逻辑。稍后我将单独测试它。 UseLogin returns 将新用户连接到 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];
}
您应该尽可能避免 mock 自己的组件,因为如果更改组件代码,您将需要同时维护组件和 mock。您仍然可以测试它并测试隔离的 useLogin
挂钩,以测试所有不同的代码分支等等。
在去往外部世界并发出 API 请求时,建议使用一个库,该库允许您在不打扰的情况下模拟它们。 nock or Mock Service Worker let you do exactly that, and this way you avoid mocking fetch.
这样的库就是说,如果您需要对此进行模拟,您可以将 firebase 库模拟为 return 所需的任何内容。您可以使用常规的 Jest 模拟来完成,或者试试这个 firebase-mock library in case you will need to mock more of firebase features and here you can see how it integrates with Jest.
创建您自己的自定义模拟可能是更快的选择,如果您不需要模拟其他任何东西,它也可能是最好的选择。在这里您可以看到自定义 firebase 模拟的示例: