reactjs - react Redux : Testing mapStateToProps and mapDispatchToProps with Enzyme/Jest

标签 reactjs redux react-redux jestjs enzyme

所以我想用 Enzyme/Jest 测试 mapStateToPropsmapDispatchToProps

我有一个像这样的组件 DrawerAvatar:

DrawerAvatar.js

const mapStateToProps = state => ({
  isAuthenticated: state.authReducer.isAuthenticated
});

export default compose(
  connect(mapStateToProps, null)
)(DrawerAvatar);

DrawerAvatar.test.js

import configureMockStore from 'redux-mock-store';
import connectedDrawerAvatar, { DrawerAvatar } from './DrawerAvatar';

const mockStore = configureMockStore();

it('mapStateToProps should return the right value', () => {
  const initialState = {
    someState: 123
  };
  const store = mockStore(initialState);
  const wrapper = shallow(<connectedDrawerAvatar store={store} />);
  expect(wrapper.props().someState).toBe(123);
});

但是,这不起作用,因为 wrapper.props().someState 返回 undefined...所以我不知道如何测试 mapStatesToProps 和 redux-使用连接的组件进行模拟存储。

我也不知道如何测试mapDispatchToProps ..! 我已经尝试过此 blog 中提供的方法但它不起作用。

非常感谢!

编辑: 这可行,但我不确定它是否真正测试ma​​pStateToProps...有人可以确认这是测试mapStateToProps的正确方法吗? DrawerAvatar.test.js

  it('mapStateToProps should return the right value', () => {
    const initialState = {
      isAuthenticated: false
    };
    const mockStore = configureMockStore();
    const store = mockStore(initialState);

    const wrapper = shallow(<connectedDrawerAvatar store={store} />);
    expect(wrapper.props().store.getState().isAuthenticated).toBe(false);
  });

最佳答案

我发现的一种方法是:redux discussion on github

import React from 'react';
import { shallow } from 'enzyme';
import configureMockStore from 'redux-mock-store';

import ConnectedDrawerAvatar from './DrawerAvatar';
describe('DrawerAvatar', ()=> {
    const mockStore = configureMockStore();

    it.each([true, false], 'receives correct value from store as props', (value)=> {
        const initialState = { authReducer: { isAuthenticated: value } }
        const store = mockStore(initialState)

        const wrapper = shallow(<ConnectedDrawerAvatar store={store} />)
        expect(wrapper.props().isAuthenticated).toBe(value)
    })
})

关于reactjs - react Redux : Testing mapStateToProps and mapDispatchToProps with Enzyme/Jest,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51943248/

相关文章:

css - Tailwind CSS - 小媒体查询被大屏幕媒体查询覆盖

javascript - 如何从我的 redux 操作向 GraphQL 服务器发出请求?

javascript - Redux 在到达 reducer 之前检测到状态突变

reactjs - React Redux 将计算存储在reducer 或action-creator 中?

javascript - react 如何处理组件中顶部边框的大小调整

reactjs - 清理 useEffect React 钩子(Hook)中的异步函数

javascript - React-Redux Dashboard 应用程序结构

javascript - 如何使用react js在select中设置默认值

javascript - 关闭 Electron 应用程序不会停止脚本

reactjs - 在 React 应用程序中使用使用 React、Redux 和 React-Redux 完成的组件并使用 Webpack 构建时出错