gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 13:36:21 24 4
gpt4 key购买 nike

所以我想用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com