如果我使用模拟商店渲染redux组件,则酶浅渲染会以意想不到的方式运行. 我有一个简单的测试,如下所示: import React from 'react'; import { shallow } from 'enzyme'; import { createMockStore } from 'redux-t
我有一个简单的测试,如下所示:
import React from 'react';
import { shallow } from 'enzyme';
import { createMockStore } from 'redux-test-utils';
import Test from './Test'
it('should render ', () => {
const testState = {
app: {
bar: ['a', 'b', 'c']
}
};
const store = createMockStore(testState)
const context = {
store,
};
const shallowComponent = shallow(<Test items={[]}/>, {context});
console.log(shallowComponent.debug());
}
Test组件如下所示:
class Test extends React.Component {
constructor(props) {
super(props);
}
render() {
return(
<div className="here"/>
)
}
}
export default Test;
正如预期的那样打印出来:
<div className="here" />
但是,如果我的组件是redux组件:
class Test extends React.Component {
constructor(props) {
super(props);
}
render() {
return(
<div className="here"/>
)
}
}
const mapStateToProps = state => {
return {
barData: state.app.bar
}
}
export default connect(
mapStateToProps
)(Test)
然后我在控制台得到的是:
<BarSeriesListTest items={{...}} barData={{...}} dispatch={[Function]} />
为什么会出现这种差异?如何测试我的组件是否具有< div className =“here”/>嵌入在我的redux版本的组件中?
您正在引用连接正在返回的HOC,而不是您要测试的组件.你应该使用酶的dive函数,它将渲染子组件并将其作为包装器返回.
const shallowComponent = shallow(< Test items = {[]} />,{context}).dive();
如果您有多个需要潜入的组件,您可以多次使用它.它也比使用mount更好,因为我们仍在单独测试.
