【问题标题】:try catch or async awaiit in useeffect for jest尝试使用 catch 或 async await 来开玩笑
【发布时间】:2022-02-13 01:38:51
【问题描述】:

我正在JEST 中运行我的第一个单元测试。我安装了Jest Fetch Mock,但仍然收到错误消息“The promise rejected with reason FetchError”。

我做了一些阅读,我想我需要添加一个 async awaittry catch。有人可以帮我解决这个问题吗?

这是我在useEffect 中制作的fetch

const [data, setData] = useState(null);
  const [isLoading, setLoading] = useState(false);

  useEffect(() => {
    setLoading(true)
    
    fetch("https://api.github.com/search/repositories?q=created:%3E2017-01-10&sort=stars&order=desc")
    .then((res) => res.json())
      .then((data) => {
        setData(data)
        setLoading(false)
      })
  }, [500]);

【问题讨论】:

    标签: javascript reactjs jestjs next.js


    【解决方案1】:
     const [data, setData] = useState(null);
     const [isLoading, setLoading] = useState(false);
    
     useEffect(async() => {
       setLoading(true)
       try{
            const res = await fetch("https://api.github.com/search/repositories?q=created:%3E2017-01-10&sort=stars&order=desc")
            const data = await res.json()
            setData(data)
            setLoading(false)
         }catch(err=>{
            console.log(err)
          })
        
       }, [500]);
    

    【讨论】:

      【解决方案2】:

      效果更好

      const fetchList = async () => {

      const newList = await fetch("https://api.github.com/search/repositories?q=created:%3E2017-01-10&sort=stars&order=desc") .then((res) => res.json()) .then((数据) => { 设置数据(数据) 设置加载(假) }) } 获取列表() }, [500]);

      【讨论】:

        【解决方案3】:

        你可以试试这个,

         const [data, setData] = useState(null);
         const [isLoading, setLoading] = useState(false);
        
         useEffect(async() => {
           setLoading(true)
           try{
                const data = await 
                  fetch("https://api.github.com/search/repositories? 
                      q=created:%3E2017-01- 
                 10&sort=stars&order=desc")
            const json = await data.json();
            if(json){
                setData(json)
                setLoading(false)
              } 
             }catch (e) {
            console.error(e);
            }
            
           }, [500]);
        

        【讨论】:

        • 您需要添加data = await data.json()
        • 是的,你是对的。我的错。我编辑了我的代码。
        • hmm 不断用意外令牌标记​​。虽然无法确定在哪里。 codesandbox.io/s/thirsty-mountain-5n0i5?file=/src/new.js
        • @shar27 我编辑了代码...请尝试一下。
        • 你知道如何在 react 中用 jest 对这段代码进行单元测试吗?
        猜你喜欢
        • 2017-07-19
        • 2017-04-14
        • 2019-08-20
        • 2020-01-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-01-02
        • 1970-01-01
        相关资源
        最近更新 更多