【发布时间】:2018-08-25 00:26:22
【问题描述】:
我有一个有条件渲染的 react 组件(如果获取数据则渲染,否则返回 null),我想用 jest & enzyme 测试它。我遇到的问题是我想测试类中的一种方法,但 .instance() 一直返回 null,因此它不允许我测试实例。
我的代码看起来像这样
export default class MyComponent extends React.Component<Props, State> {
componentDidMount() {
this.props.fetchData.then(() =>
this.setState({ loaded: true });
);
}
methodThatIWantToTest() {
//do some stuff here
}
render() {
if (this.loaded) {
// render stuff here
} else {
return null;
}
}
}
在测试中我想测试
describe('myComponent', () => {
it('should do some stuff', () => {
const shallowWrapper = shallow(<MyComponent {...props}/>);
const method = shallowWrapper.instance().methodThatIWantToTest();
....such and such
});
});
但看起来MyComponent 只返回null,所以shallowWrapper.instance() 也返回null。我尝试了shallowWrapper.update() 和许多其他的东西,但它似乎根本不想渲染。我如何等待我的组件更新然后启动expect 语句?
有没有人遇到过和我类似的问题并且知道如何解决这个问题?
【问题讨论】:
-
您能否尝试在您的渲染方法中不返回
null,而是返回<div />?