我正在尝试使用shallow https://github.com/airbnb/enzyme/blob/master/docs/api/shallow.md from enzyme https://github.com/airbnb/enzyme并且还使用快照 https://facebook.github.io/jest/docs/en/snapshot-testing.html from jest https://facebook.github.io/jest/一起。
我面临的问题是我需要使用以下命令更改状态中的某些内容setState()
from enzyme https://github.com/airbnb/enzyme/blob/master/docs/api/ShallowWrapper/setState.md然后将结果与快照进行匹配。
查看我的组件的代码:
....
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 传递的产品是否存在。
这就是为什么我需要酶来改变状态。那么,如果匹配的话,<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
and create
:
const component = <Component nextProps={nextProps} />;
shallow(component).instance()).instance()
create(component).toJSON()`
我也尝试过但没有运气酶转 json https://github.com/adriantoine/enzyme-to-json.
你会怎么办?