用酶测试重组HOC

时间:2017-07-26 12:16:27

标签: javascript reactjs jestjs enzyme recompose

如何(使用jest + enzyme)测试以下使用recompose创建HoC的代码:

import {compose, withState, withHandlers} from 'recompose'

const addCounting = compose(
  withState('counter', 'setCounter', 0),
  withHandlers({
    increment: ({ setCounter }) => () => setCounter(n => n + 1),
    decrement: ({ setCounter }) => () =>  setCounter(n => n - 1),
    reset: ({ setCounter }) => () => setCounter(0)
  })
)

执行浅渲染时,我可以访问countersetCounter属性,如下所示:

import {shallow} from 'enzyme'

const WithCounting = addCounting(EmptyComponent)
const wrapper = shallow(<WithCounting />)

wrapper.props().setCounter(1)
expect(wrapper.props().counter).toEqual(1)

最大的问题是,如何访问处理程序(incrementdecrementreset)并调用它们?它们不会出现在wrapper.props()

1 个答案:

答案 0 :(得分:6)

所以你可以先找到实例来访问道具:

const EmptyComponent = () => null;
const WithCounting = addCounting(props => <EmptyComponent {...props} />);
const wrapper = mount(<WithCounting />);

wrapper.find(EmptyComponent).props().setCounter(1);
expect(wrapper.find(EmptyComponent).props().counter).toEqual(1);