【问题标题】:How to unit test with redux selectors如何使用 redux 选择器进行单元测试
【发布时间】:2021-05-28 19:27:32
【问题描述】:

我目前正在对该文件进行单元测试,但我不知道如何对 redux 中的两个常量(网格和列表)进行单元测试。

文件

const Projects = () => {
  const dispatch = useDispatch();
  const view = useSelector(selectView);

  useMount(() => {
    dispatch(projectsActions.viewRestore());
    dispatch(projectsActions.filterRestore());
  });

  return (
    <Wrapper>
      <div className="projects-toolbar" data-testid="projects-toolbar-container">
        <Toolbar />
      </div>

      {view === VIEW_TYPES.grid && <ProjectsGridView />}
      {view === VIEW_TYPES.list && <ProjectsListView />}
    </Wrapper>
  );
};

测试文件

    test('renders properly', () => {
    const { getByTestId,  } = setup();

    expect(getByTestId('projects-toolbar-container')).toBeInTheDocument();
  });

正如你们看到的,我唯一能做的测试是在工具栏组件的外部 div 中添加一个 ID,以查看它是否存在,但除此之外,我不知道如何检查常量是否匹配以呈现其他 2 个组件

【问题讨论】:

    标签: reactjs unit-testing jestjs react-testing-library


    【解决方案1】:

    在测试使用 redux 的组件时。您可以使用这个库redux mock store,它可以帮助您模拟存储值。

    现在你可以在你的测试文件中做

    import {Provider} from 'react-redux';
    import configureStore from 'redux-mock-store';
    
    const mockStore = configureStore([]);
    
    const store = mockStore({
        view: 'your value here' // now your component will use this value
    });
    

    现在在你的测试文件的渲染中用

    包裹你的组件
     <Provider store={store}>
            <Projects /> 
     </Provider>
    

    注意

    请注意,此库旨在测试与动作相关的逻辑,而不是与减速器相关的逻辑。换句话说,它不会更新 Redux 存储。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-29
      • 2019-12-25
      • 1970-01-01
      相关资源
      最近更新 更多