【发布时间】:2017-11-17 08:51:08
【问题描述】:
我正在尝试同时使用 enzyme 中的 shallow 和 jest 中的 snapshots。
我面临的问题是我需要使用 setState() 从 enzyme 更改状态,然后将结果与快照匹配。
查看我的组件的代码:
....
getPrevProduct = () => {
const key = this.state.indexCurrent > 0 &&
this.productsKeys[this.state.indexCurrent - 1];
let product = null;
if (key) {
product = this.props.products[key];
}
return product;
}
renderPrev = () => this.getPrevProduct() && <PrevButton />;
render() {
return (
<div>
...
{this.renderPrev()}
...
<div>
)
}
前面的代码检查从 currentIndex 中的 props 传递的产品是否存在。
这就是为什么我需要 Enzyme 来改变状态。然后,如果匹配,<PrevButton /> 必须被渲染。
这个测试是我想将组件与快照匹配:
const nextProps = {
products: {
test: 'test'
}
};
const tree = create(<Component nextProps={nextProps} />).toJSON();
expect(tree).toMatchSnapshot();
但我需要更改状态。我怎么能这样做?这不起作用:
it('should render component with prev button', () => {
const nextProps = {
products: {
test: 'test'
}
};
const instance = shallow(<Component nextProps={nextProps} />).instance()
instance.setState({
indexCurrent: 1
});
const tree = create(<Component nextProps={nextProps} />).toJSON();
expect(tree).toMatchSnapshot();
});
我还尝试将组件的声明保存到变量中,就像下一个未完成的代码一样,并在shallow和create中使用它:
const component = <Component nextProps={nextProps} />;
shallow(component).instance()).instance()
create(component).toJSON()`
我也试过了,没有运气enzyme-to-json。
你会怎么做?
【问题讨论】:
标签: javascript reactjs unit-testing jestjs enzyme