React jest 测试错误 - useContext 对象未定义

Mar*_*all 3 unit-testing reactjs jestjs react-testing-library use-context

希望你们在这种情况下一切顺利:) 在 React 应用程序的 App 组件中运行渲染测试时,我在 useContext 中遇到错误。

  • 这是上下文 api

    const { userId } = useContext(UserContext);

  • 这是错误

    TypeError:无法解构“(0,_react.useContext)(...)”的属性“userId”,因为它未定义。

    35 | 35 const { userId } = useContext(UserContext);

该对象一开始是未定义的,因为它是获取 userId 的 API 调用。登录后,用户 ID 可用。因此,在开发中运行时,它可以正常工作,但在运行测试时,它会显示此错误。

  • 最后是 UserContext 组件:

    导出 const UserContext = createContext();

     const UserProvider = ({ children }) => {
       const [userId, setUserId] = useState("");
       const getUserId = async () => {
         if (token) {
           await axios
             .get(`${baseURL}/auth/user`, {
               headers: {
                 authorization: token
               }
             })
             .then(function (response) {
               const { data } = response;
               return setUserId(data.userId);
             })
             .catch(function (err) {
               if (err.response)
                 return toast.error(
                   <div>
                     <InfoIcon style={{ marginBottom: "6px" }} />
                     <p>
                       getUserId - {err.response.status} - {err.response.message}
                     </p>
                   </div>
                 );
               return toast.error(
                 <div>
                   <InfoIcon style={{ marginBottom: "6px" }} />
                   <p>User Context - CORS</p>
                 </div>
               );
             });
         }
       };
       useEffect(() => {
         getUserId();
       }, []);
    
       return (
         <UserContext.Provider value={{ userId }}>{children}</UserContext.Provider>
       );
     };
     export default UserProvider;
    
    Run Code Online (Sandbox Code Playgroud)

小智 7

我需要查看您的 test.js 文件。但是您应该在测试文件中渲染用上下文组件包装的组件,以避免在没有它的情况下渲染时出现错误。在您的情况下,您应该: render(<UserProvider><App /></UserProvider> 在您的 test.js 文件中。