Skip to content

Instantly share code, notes, and snippets.

@brendanmoore
Created January 25, 2018 13:46
Show Gist options
  • Save brendanmoore/c296c7341dae8ff9871863ff7495a359 to your computer and use it in GitHub Desktop.
Save brendanmoore/c296c7341dae8ff9871863ff7495a359 to your computer and use it in GitHub Desktop.
Async React, Jest + Enzyme tests example
/**
* @jest-environment jsdom
*/
import React, { Component } from "react";
import { mount } from "enzyme";
const Updated = () => <div>Updated!</div>;
class TimeoutComponent extends Component {
state = {
updated: false
};
componentDidMount() {
setTimeout(
() =>
this.setState({ updated: true }, () =>
console.log("State Updated!")
),
1
);
}
render() {
return <div>{this.state.updated && <Updated />}</div>;
}
}
class ImmediateComponent extends Component {
state = {
updated: false
};
componentDidMount() {
setImmediate(() =>
this.setState({ updated: true }, () =>
console.log("State Updated!")
)
);
}
render() {
return <div>{this.state.updated && <Updated />}</div>;
}
}
class NextTickComponent extends Component {
state = {
updated: false
};
componentDidMount() {
process.nextTick(() =>
this.setState({ updated: true }, () =>
console.log("State Updated!")
)
);
}
render() {
return <div>{this.state.updated && <Updated />}</div>;
}
}
class PromiseComponent extends Component {
state = {
updated: false
};
componentDidMount() {
Promise.resolve().then(() =>
this.setState({ updated: true }, () =>
console.log("State Updated!")
)
);
}
render() {
return <div>{this.state.updated && <Updated />}</div>;
}
}
describe("Async mounting", () => {
[
TimeoutComponent,
ImmediateComponent,
NextTickComponent,
PromiseComponent
].forEach(AsyncComponent => {
it(`${AsyncComponent.name} Should render the updated component`, async () => {
jest.useFakeTimers();
const wrapper = await mount(<AsyncComponent />);
jest.runAllTimers();
console.log(wrapper.html());
expect(wrapper.html()).toBe("<div><div>Updated!</div></div>");
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment