如何使用useReducer挂钩测试组件?

时间:2019-12-10 21:14:16

标签: reactjs react-hooks enzyme react-hooks-testing-library

减速器

// src/reducers/FooReducer.js

export function FooReducer(state, action) {
  switch (action.type) {
    case 'update': {
      return action.newState;
    }
// ... other actions
    default:
      throw new Error('Unknown action type');
  }
}

组件

// src/components/BarComponent.js

export function BarComponent() {
  const [state, dispatch] = useReducer(FooReducer, []);

  return (
    {state.map((item) => (<div />))}
  );
}

测试

// src/components/BarComponent.test.js

it('should render as many divs as there are items', () => {
  act(() => {
    const { result } = renderHook(() => useReducer(FooReducer, [1]));
    const [, dispatch] = result.current;
    wrapper = mount(<BarComponent />);
    dispatch({type: 'update', newState: [1, 2, 3]});
  });

  expect(wrapper.find(div)).toHaveLength(3);
});

以上测试示例不起作用,但可用于演示我正在尝试实现的目标。并且实际上将渲染0 div,因为组件中声明的初始状态包含0个项目。

  1. 我将如何修改reducer的状态或更改为测试目的而部署的reducer状态?

  2. 我习惯于在多个组件中使用Redux减速器,但是useReducer需要传递一个initialState ...这引发了一个问题:react-hook的减速器可以作为单个实例通过多个组件使用,还是总是2单独的实例?

1 个答案:

答案 0 :(得分:1)

在您的示例中,您尝试同时测试两件事,最好将它们作为单独的测试进行测试:减速器的单元测试和组件使用减速器的组件测试。

  
      
  1. 我将如何修改reducer的状态或更改为测试目的而部署的reducer状态?
  2.   

类似于Redux缩减器,因为您将其导出为纯函数,所以简化器易于进行单元测试。只需将您的初始状态传递给state参数,然后将您的操作传递给action

it('returns new state for "update" type', () => {
  const initialState = [1];
  const updateAction = {type: 'update', newState: [1, 2, 3] };
  const updatedState = fooReducer(initialState, udpateAction);
  expect(updatedState).toEqual([1, 2, 3]);
});

如果您愿意,还可以在useReducer的上下文中对其进行测试:

it('should render as many divs as there are items', () => {
  act(() => {
    const { result } = renderHook(() => useReducer(FooReducer, [1]));
    const [state, dispatch] = result.current;
    dispatch({type: 'update', newState: [1, 2, 3]});
  });

  expect(state).toEqual([1, 2, 3]);
  // or expect(state).toHaveLenth(3) if you prefer
});
  
      
  1. 我已经习惯了Redux减速器在多个组件中使用,但是useReducer需要传递一个initialState ...这引发了一个问题:react-hook的减速器可通过多个组件作为单个实例使用,还是总是两个单独的实例?
  2.   

这是useReducer与Redux的不同之处:您可以重用化简器本身,但是如果您有多个useReducer,则分别返回statedispatch以及初始状态都是单独的实例。

为了测试在减速器更新时BarComponent是否更新,您将需要一种从组件内部触发dispatch的方法,因为您要在组件内部调用useReducer。这是一个示例:

export function BarComponent() {
  const [state, dispatch] = useReducer(FooReducer, []);

  const handleUpdate = () => dispatch({type: 'update', newState: [1, 2, 3]})

  return (
    <>
      {state.map((item) => (<div />))}
      <button onClick={handleUpdate}>Click to update state</button>
    </>
  );
}
it('should render as many divs as there are items', () => {
  wrapper = mount(<BarComponent />);

  expect(wrapper.find('div')).toHaveLength(0);

  wrapper.find('button').simulate('click');

  expect(wrapper.find('div')).toHaveLength(3);
});

这可能不太现实,因为我正在组件本身中对新数组进行硬编码,但希望它能为您提供想法!

相关问题