如果我使用mocked store渲染redux组件,酶浅渲染会以一种意想不到的方式出现。
我有一个简单的测试,看起来像这样:
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]} />为什么会有这样的差异呢?我如何在我的redux版本中测试我的组件是否嵌入了<div className="here"/>?
发布于 2017-10-27 03:10:17
您引用的是connect返回的HOC,而不是您要测试的组件。
您应该使用enzyme的dive函数,该函数将渲染子组件并将其作为包装器返回。
const shallowComponent = shallow(<Test items={[]}/>, {context}).dive();
如果您有多个需要深入研究的组件,则可以多次使用它。它也比使用mount更好,因为我们仍然是在隔离中测试。
发布于 2017-10-31 21:16:05
您应该导出未连接的组件并单独测试它(请注意第一个export):
export class Test extends React.Component {
}
...
export default connect(
mapStateToProps
)(Test)在测试中,您应该像这样测试未连接组件的呈现(请注意{ Test }周围的花括号):
import React from 'react';
import { shallow } from 'enzyme';
import toJson from 'enzyme-to-json';
import { Test } from './Test';
describe('...', () => {
it('...', () => {
const wrapper = shallow(<Test />)
expect(toJson(wrapper)).toMatchSnapshot();
})
})希望这能有所帮助。
特定于您所描述的情况的模式组件应为:
import React from 'react';
import { connect } from 'react-redux';
export 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)测试规范应该是:
import React from 'react';
import { shallow } from 'enzyme';
import toJson from 'enzyme-to-json';
import { Test } from 'Test';
describe('Test component', () => {
it('renders', () => {
const wrapper = shallow(<Test />);
expect(toJson(wrapper)).toMatchSnapshot();
});
});它会生成以下快照:
exports[`Test component renders 1`] = `
<div
className="here"
/>
`;发布于 2017-10-31 21:43:30
默认情况下,将导出连接的构件。您可以做的是导入未连接到redux的组件。
import { Test } from './Test';那么你的测试应该可以工作了。
https://stackoverflow.com/questions/46875547
复制相似问题