R
R
Roman Chasovitin2019-07-04 14:47:53
JavaScript
Roman Chasovitin, 2019-07-04 14:47:53

How to work with React Hooks in jest/enzyme tests?

I have a component that has a useState and an updateTotalSum function that triggers setTotalSum. How can I test and get value from useState(totalSum) and also call updateTotalSum function

//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

// Пример теста для компонента-класса. Все корректно работает.
it('should correctly called updateTotalSum method', () => {
  const wrapper = shallow(<SomeComponent />;
  wrapper.instance().updateTotalSum(1000);
  expect(wrapper.state('totalSum')).toBe(1000);
});

// Тест для функционального компонента. Ожидаемо, не работает
it('should correctly called updateTotalSum method', () => {
  const wrapper = shallow(<SomeComponent />;
  wrapper.updateTotalSum(1000);
  expect(wrapper.totalSum).toBe(1000);
});

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
miliko mikoyan, 2019-07-04
@miliko0022

Enzyme doesn't support hooks yet.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question