使用酶测试第二次useEffect调用

时间:2020-03-30 01:31:50

标签: reactjs react-hooks enzyme

我有一个组件,该组件进行初始调用以获取数据并发送给子组件。还将处理程序传递给子组件,该子组件由子回调,触发获取更新数据。为此,我试图编写一个测试以覆盖代码。到目前为止,尚无法为此组件编写适当的测试。

//Source File

function MyComponent() {
  const [users, setUsers] = useState([]) ;
  const [companies, setCompanies] = useState([]) ;
  const [fetchData, setFetchData] = useState(undefined);

  const handleOnSave = () => setFetchdata(true);

  const fetchUsers = async () => {
    await fetch('/users')
      .then(...) //setUsers(response.values) on success
      .catch(...) //handle error case      
  };

  const fetchCompanies = async () => {
    await fetch('/companies')
      .then(...) //setCompanies(response.values) on success
      .catch(...) //handle error case
  };

  React.useEffect(() => {
        Promise.all([fetchUsers(), fetchCompanies()]);
    }, [fetchData]);

  return (
    <MyChildComponent users={users} companies={companies} saveHandler={handleOnSave}/>    
  )
}
//Test File

it('should refetch', () => {
  //had to set this stub to call all fetch
  const useEffect = sinon.stub(React, 'useEffect');

  useEffect.onCall(0).callsFake((f) => f());
  useEffect.onCall(1).callsFake((f) => f());
  useEffect.onCall(2).callsFake((f) => f());
  useEffect.onCall(3).callsFake((f) => f());

  fetchMock
    .get('/users', { values: expectedUsers })
    .get('/users', { values: expectedUpdatedUsers }, { overwriteRoutes: false });
  fetchMock
    .get('/companies', { values: expectedCompanies })
    .get('/companies', { values: expectedUpdatedCompanies }, { overwriteRoutes: false });

  const renderedElement = enzyme.shallow(<MyComponent/>);
  renderedElement.props().saveHandler();
  await fetchMock.flush(true);

  expect(renderedElement.props().users).to.be.eql(expectedUpdatedUsers);
  expect(renderedElement.props().companies).to.be.eql(expectedUpdatedCompanies);  
});

我要编写的测试是确保使用更新的用户和公司数据调用MyChildComponent组件。我从该测试中得到的所有信息都将是不确定的。有什么建议吗?

谢谢

0 个答案:

没有答案