Skip to content

Instantly share code, notes, and snippets.

@ebuildy
Created February 27, 2019 10:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ebuildy/8df75bcbea97a71c7b35dd2eeba473b2 to your computer and use it in GitHub Desktop.
Save ebuildy/8df75bcbea97a71c7b35dd2eeba473b2 to your computer and use it in GitHub Desktop.
Async React component testing with jest & enzyme
import { shallow, mount, configure, render } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import waitUntil from 'async-wait-until';
configure({ adapter: new Adapter() });
global.exceptRenderFine = async (component) => {
// full mount the component (shallow can work and will be faster)
const root = mount(component)
try {
// Wait to isReady become true
await waitUntil(() => root.state('isReady'), 500, 10)
// Force component render
root.update()
// Compare HTML with previous snapshot
expect(root.html()).toMatchSnapshot();
} catch(error) {
throw error
}
}
import React from "react";
import PropTypes from "prop-types";
import { palettes } from "@elastic/eui/lib/services";
import moment from "moment";
import humanizeDuration from "humanize-duration";
import { config, getElementAbsoluteOffset } from "../../utils";
import LogDataService from '../../services/LogDataService';
const paletteData = palettes.euiPaletteColorBlind.colors;
const colorSuccess = paletteData[0];
const colorError = paletteData[2];
export default class JobsExecutionTimeline extends React.Component {
static propTypes = {
date: PropTypes.object.isRequired
};
constructor(props) {
super(props);
this.$tooltip = React.createRef();
this.$wrapper = React.createRef();
this.state = {
isReady: false,
....
};
}
componentDidMount() {
this.getData();
}
getData() {
if (this.props.date && this.$wrapper.current) {
LogDataService.search({
....
})
.then(response => {
this.setState({
error: null,
isLoaded: true,
items: response.hits.hits.map((h, i) => ({ ...h._source, id: h._id, position: i })),
....
isReady: true // HERE, we declare our component is ready !
});
});
}
}
render() {
return (....)
}
}
// The component to test
import JobsExecutionTimeline from '../timeline';
// The data service to mock (fake HTTP call)
jest.mock('services/LogDataService')
import LogDataService from 'services/LogDataService';
it('renders without data', async () => {
// Fake data
LogDataService.setSearchCallback({
hits: {
hits: []
},
aggregations: {
date_min: {
value_as_string: "2018-01-01 00:00:00"
},
date_max: {
value_as_string: "2018-01-01 01:00:00"
}
}
})
// Wait
await exceptRenderFine(<JobsExecutionTimeline date={dd} />)
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment