问题描述
我需要模拟useLogin钩子,因为它包含引发错误的逻辑.稍后我将对其进行隔离测试.UseLogin返回将新用户连接到Firebase的加载标志和登录功能.
I need to mock useLogin hook, bacause it contains logic that throws an error. Later i will test it in isolationю. UseLogin returns loading flag and login function that connecting new user to firebase.
import useLogin from "../../../hooks/useLogin";
export default function Login({ register, handleSubmit }) {
const [loading, login] = useLogin();
return (
<Form onSubmit={handleSubmit(login)}>
{...other components}
<Form>
);
}
useLogin钩子
useLogin hook
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];
}
推荐答案
在可能的情况下,应避免对自己的组件进行模拟,因为如果更改组件代码,则需要同时维护组件和模拟.您仍然可以对此进行测试,并测试隔离的 useLogin
钩子,以测试所有不同的代码分支,等等.
You should avoid mocking your own components when possible, as you will need to maintain both component and mock if you change the component code. You can still test this and test the useLogin
hook isolated, to test all different code branches and so on.
当您向外界提出API请求时,建议使用一个库,该库允许您模拟它们而不会造成干扰.像 nock 或模拟服务工作者可以让您做到这一点,这样,您避免模拟提取.
The recommendation when going to the outside world and make API requests, is to use a library that allows you to mock them without being intrusive. Libraries like nock or Mock Service Worker let you do exactly that, and this way you avoid mocking fetch.
也就是说,如果您需要对此进行模拟,则可以对firebase库进行模拟以返回所需的任何内容.您可以使用常规的Jest模拟来完成此操作,或者尝试使用 firebase-mock 库您将需要模拟更多的Firebase功能,并在在这里可以看看它如何与Jest集成.
That said, in case you need to mock this, you can mock the firebase library to return whatever is needed. You can do it with a regular Jest mock, or try this 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模拟的示例:
Creating your own custom mock might be the quicker option, and if you don't need to mock anything else, it might be the best option as well. Here you can see an example of a custom firebase mock: Mock implementation of firebase auth methods after mocking the firebase module
这篇关于模拟反应自定义钩的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!