I'm trying to use shallow from enzyme and also use snapshots from jest together.
The problem I'm facing is that I need to change something from the state using setState() from enzyme and then match the result with the snapshot.
See the code of my component:
....
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>
)
}
The previous code checks if the product, passed from props in the currentIndex, exists.
That's why I need Enzyme to change the state. Then, if it matches, <PrevButton /> has to be rendered.
This test is when I want to match the component with the snapshot:
const nextProps = {
products: {
test: 'test'
}
};
const tree = create(<Component nextProps={nextProps} />).toJSON();
expect(tree).toMatchSnapshot();
But I need to change the state. How I can do that? This doesn't work:
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();
});
I also tried to save the declaration of the component into a variable like the next uncompleted code and use it in shallow and create:
const component = <Component nextProps={nextProps} />;
shallow(component).instance()).instance()
create(component).toJSON()`
I also tried with no luck enzyme-to-json.
What would you do?