7

如何测试(使用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()

4

1 回答 1

7

因此,您可以通过首先找到实例来访问道具:

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);
于 2017-07-28T10:20:38.727 回答