我正在尝试使用 shallow来自 enzyme并使用 snapshots来自 jest在一起。
我面临的问题是我需要使用 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 .
你会怎么做?
最佳答案
可能,这不是 enzyme-to-json
应该使用的方式。试试这个方法:
import { shallowToJson } from 'enzyme-to-json';
import { shallow } from 'enzyme';
然后在你的测试中:
const wrapper = shallow(<Component />);
expect(shallowToJson(wrapper)).toMatchSnapshot();
关于javascript - 如何将 Enzyme Shallow 与 Jest 快照一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47346574/