嵌套函数reactjs的Jest测试用例

时间:2020-08-24 18:46:57

标签: reactjs jestjs

我有一个从子组件触发的onClick函数。 onClick函数更新父组件中的状态。

function ParentComponent({str}){

const [abc, setAbc] = useState("");
const [def, setDef] = useState(false);

const funcn = () => {
   setAbc(getRamdomString(str));
   setDef(true);
};

return(
  <div>
     <ChildComponent funcn={funcn}/>
  </div>
)
}

我尝试了以下操作

  it('animation on answer fetch', () => {
      const mountedComp = mount(<ThisComponent />)
      const getRandomString = jest.fn((arr) => "answer");
      const setDef = jest.fn(() => true);
      const setAbc= jest.fn(()=> getRandomString ("ans"));
      const useStateSpy = jest.spyOn(React, 'useState')
      useStateSpy.mockImplementation(init=> [init, setAbc]);
      const getThat = jest.fn(() => {
             setAbc(getRandomString(["answer"])); setDef()                                                                                            
           });
      mountedComp.find('button').at(0).simulate('click');
      expect(getThat).toBeCalled(); 
      expect(setAbc).toHaveBeenCalled();
      expect(setDef).toHaveBeenCalled();
   });

我无法涵盖点击功能

const funcn = () => {
   setAbc(getRamdomString(str));
   setDef(true);
};

请帮助。

0 个答案:

没有答案