gpt4 book ai didi

reactjs - 使用 enzyme 获取连接到 redux 的子组件的状态

转载 作者:行者123 更新时间:2023-12-03 14:01:20 25 4
gpt4 key购买 nike

我正在尝试测试 redux 连接组件。组件在调整大小事件时更改其属性。

我想用 enzyme 挂载我的 DatePicker 组件,调度调整大小事件,并测试我的 DatePicker 的 prop 值 IS_DESKTOP_VIEWPORT === true ,因此,我的 DatePicker 的状态也发生了变化。

但是,我无法访问 DatePicker 的状态,因为如果包装器组件不是根组件, enzyme 将不允许您访问该状态:

console.log(wrapper.find('DatePicker').state())
// ReactWrapper::state() can only be called on the root

我尝试按照文档的建议将连接的 DatePicker 包装在 Provider 中,以及直接安装它但将 store 作为 prop 传递。这两种方法似乎都不允许我将 DatePicker 引用为根组件,因此这两种方法都不允许我获取组件的状态。

这是我的尝试:这些控制台日志的输出如下:https://gist.github.com/gecko25/56fb14154585a2d06697c399685c9111

import React from 'react';
import { Provider } from 'react-redux';
import PropTypes from 'prop-types';
import { mount } from 'enzyme';
import configureDataStore from '%SRC%/store/configure';
import { windowResize } from '%CONSTANTS%/store/actions';
import ConnectedDatePicker, { DatePicker } from './DatePicker';

const DESKTOP = 1025;

describe('calendar open and closes', () => {

test('connected attempt #1', ()=>{

const store = configureDataStore();

const options = {
context: { store },
childContextTypes: { store: PropTypes.object }
}

const wrapper = mount(<ConnectedDatePicker store={store}/>)

store.dispatch(windowResize(DESKTOP));

console.log('state-->', wrapper.state()) // {}
console.log('props-->', wrapper.props()) // Doesn't include all my component specific props
console.log(wrapper.find('DatePicker').props()) // Prints all props as expected
console.log(wrapper.find('DatePicker').state()) // Error

console.log('--------------------------')

})

test('connected attempt #2', () => {

const store = configureDataStore();

const options = {
context: { store },
childContextTypes: { store: PropTypes.object }
}

const wrapper = mount(<ConnectedDatePicker/>, options)

store.dispatch(windowResize(DESKTOP));


console.log('state-->', wrapper.state()) // {}
console.log('props-->', wrapper.props()) // Doesn't include all my component specific props
console.log(wrapper.find('DatePicker').props()) // Prints all props as expected
console.log(wrapper.find('DatePicker').state()) // Error

});

test('connected attempt #3', () => {

const store = configureDataStore();

const wrapper = mount(<Provider store={store}><ConnectedDatePicker/></Provider>)

store.dispatch(windowResize(DESKTOP));

console.log('state-->', wrapper.state()) // null
console.log('props-->', wrapper.props()); // Doesn't include all my component specific props
console.log(wrapper.find('DatePicker').props()) // Prints all props as expected
console.log(wrapper.find('DatePicker').state()) // Error
console.log('--------------------------')

});
});

最佳答案

wrapper.find('DatePicker').instance().state 应该适合你:)

关于reactjs - 使用 enzyme 获取连接到 redux 的子组件的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44597425/

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