【问题标题】:testing react-redux useSelector测试 react-redux useSelector
【发布时间】:2020-05-17 13:42:00
【问题描述】:

我有一个 react 应用程序,它使用 react-redux、useSelector 从商店获取数据。 反应组件有

function PersonDataView() {
  const name= useSelector(state => state.data.name)
  const dob= useSelector(state => state.data.dob)
  const dispatch = useDispatch()
  const show= () => dispatch({type: 'SHOW'})
  const remove= () => dispatch({type: 'REMOVE'})
  return (
    <div>
      <h2>Person Details</h2>
     <div>
      <button onClick={show}>Show</button>
      <span aria-label="name">{name}</span>
      <span aria-label="dob">{dob}</span>
      <button onClick={remove}>Remove</button>
     </div>
   </div>
  )
}

我正在使用 react-testing-library 来测试这个组件。是否有任何 API 可以让我们更轻松地测试这些组件。我知道两种测试方法: 1)我可以使用 redux-mock-store 模拟商店,然后将此组件包装在提供程序组件下。 2)开玩笑地模拟useSelector方法

jest.mock('react-redux', () => ({
  useSelector: () => ({
  })
});

但是使用 jest mock 的问题是在多个选择器的情况下,所有的 useSelector 都会返回相同的模拟值。 使用开玩笑的模拟方式, jest.fn().mockReturnValueOnce() 对我来说看起来不正确。

【问题讨论】:

    标签: reactjs unit-testing react-redux react-hooks


    【解决方案1】:

    我会建议不同的方法 - 将您的选择器提取到单独的文件中,例如文件选择器.js:

    const nameSelector = state => state.data.name;
    const dobSelector = state => state.data.dob;
    

    然后在测试中,你可以模拟 useSelector 如下:

    jest.mock('react-redux', () => ({
      useSelector: jest.fn().mockImplementation(selector => selector()),
    }));
    

    分别模拟选择器,如:

    jest.mock('./selectors.js', () => ({
      nameSelector: jest.fn().mockReturnValue("myTestName"),
      dobSelector: jest.fn().mockReturnValue("myTestDob"),
    }));
    

    【讨论】:

      【解决方案2】:

      试试这个:

      jest.mock('react-router');
      const useSelectorMock = useSelector as any;
      
      describe('something', () {
      
      test('name', () => {
      
      // Use this for each useSelector call:
      useSelectorMock.mockImplementationOnce(jest.fn(() => returnValue as yourType));
      }
      
      }
      

      【讨论】:

        【解决方案3】:

        试试这个方法:

        jest.mock('react-redux', () => ({
          useSelector: jest.fn().mockImplementation(func => func(store))
        });
        

        您还应该在此处添加一层:

        jest.mock('react-redux', () => {
          const store = {
            data: {
              name: { 
                   ...
              },
              dob: {
                   ...
              }
            }
          };
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-09-03
          • 2019-12-19
          • 2022-12-01
          • 2020-12-06
          • 1970-01-01
          • 1970-01-01
          • 2021-05-27
          • 1970-01-01
          相关资源
          最近更新 更多