I find Jest to be very useful when testing my Redux React application. However, there are many examples of how to test async action creators, but I can't really figure out how to snapshot async components.
What I would like to do is something similar to the hovered link example from Facebook's own tutorial. They call a props function onMouseEnter() and subsequently take the snapshot. Is there an easy way to do that if onMouseEnter() dispatches an async action created with Redux Thunk?
This is how my thunk looks like, which uses axios.
// test-api.js
export function getLinkInfo() {
return function(dispatch) {
return axios.get('/api/get-link-info')
.then(response => {
dispatch(getLinkInfoSuccess(response.data));
return response;
});
};
}
Here comes my own Link component.
import React from 'react';
import { connect } from 'react-redux';
import * as api from '../../api/test-api';
class Link extends React.Component {
render() {
return (
<a href='#' onMouseEnter={this.props.getLinkInfo}>
Hover me
</a>
<div>{this.props.linkInfo}</div>
);
}
}
const mapDispatchToProps = function(dispatch) {
return {
getLinkInfo: function() {
dispatch(api.getLinkInfo());
}
}
}
const mapStateToProps = function(store) {
return {
linkInfo: store.getIn(['testState', 'linkInfo'], "")
};
};
export default connect(mapStateToProps, mapDispatchToProps)(Link);
And at last the test file.
import React from 'react';
import Link from '../link';
import renderer from 'react-test-renderer';
test('Link changes linkInfo when hovered', () => {
const component = renderer.create(
<Link></Link>
);
let tree = component.toJSON();
expect(tree).toMatchSnapshot();
// manually trigger the callback
tree.props.onMouseEnter();
// re-rendering
tree = component.toJSON();
expect(tree).toMatchSnapshot();
});