【问题标题】:How to test setState after getting response from an api从 api 获得响应后如何测试 setState
【发布时间】:2021-01-18 07:29:50
【问题描述】:

我在我的 reactjs 代码上使用 jest 和酶进行单元测试,其中我有主要功能组件“TrashDisplayFiles”,其中有一个方法“getDeletedData”,我调用了通过获取响应来设置 TrashFileState 的 api一个 API。

function TrashDisplayFiles(props){
      const[TrashFileState,setTrashFileState]=useState([]);
 //API CALL
  useEffect(()=>{
    getDeletedData();
  },[]);
const getDeletedData=()=>{ 
 trackPromise(
  Axios.get(getUrl(),
    {headers:{
    Authorization: `Basic ${btoa(getToken())}`
     }}).then((response) => {
      let FileData=response.data;
      setPaginationDefault(response.data.list.pagination)
      setTrashFileState(response.data.list.entries.map(d=>{
        return {
          select:false,
          id:d.entry.id,
          name:d.entry.name
        }})) 
      }).catch(err=>alert(err))
  )
};

我如何对这个 setTrashFileState(response.data.list.entries.map(d=>{return{ 和错误警报进行单元测试,以便它在我的覆盖率报告中得到覆盖

另外,我的 jsx 中没有通过 onsubmit 或 onclick 模拟此功能,当垃圾页面加载时,此 api 会自动触发。

【问题讨论】:

    标签: reactjs jestjs enzyme moxios


    【解决方案1】:

    你不能像这样测试 React 函数的状态,你只能测试组件的行为(我认为这总是更好的方法)。

    当然,您稍后会在代码中的某个地方使用这个TrashFileState,可能在render 中。所以测试一下使用的结果!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-14
      • 1970-01-01
      • 2020-08-25
      • 2022-11-23
      • 2015-10-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多