如何在玩笑/酶测试中使用React Hooks?

时间:2019-07-04 13:06:40

标签: reactjs

我有一个具有useState的组件和一个触发setTotalSum的updateTotalSum函数。如何测试并从useState(totalSum)获取值,并调用updateTotalSum函数

//My component

const SomeComponent = props => {
  const [totalSum, setTotalSum] = useState(null);

  const updateTotalSum = sum => {
  //...do something
  setTotalSum(sum);
  }

  return <AnotherComponent updateTotalSum={updateTotalSum} totalSum={totalSum} />
}

//My tests

// Sample test for component class. Everything works correctly.
it('should correctly called updateTotalSum method', () => {
  const wrapper = shallow(<SomeComponent />;
  wrapper.instance().updateTotalSum(1000);
  expect(wrapper.state('totalSum')).toBe(1000);
});

// Test for the functional component. Expected, not working
it('should correctly called updateTotalSum method', () => {
  const wrapper = shallow(<SomeComponent />;
  wrapper.updateTotalSum(1000);
  expect(wrapper.totalSum).toBe(1000);
});

0 个答案:

没有答案