Skip to content

Instantly share code, notes, and snippets.

@bruceharris
bruceharris / App.js
Last active Mar 2, 2018
React Unit Testing Example 17
View App.js
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import LoadingIndicator from './components/LoadingIndicator';
class App extends Component {
state = {
isLoading: true,
};
@bruceharris
bruceharris / LoadingIndicator.test.js
Created Mar 2, 2018
React Unit Testing Example 17
View LoadingIndicator.test.js
describe('on unmount', () => {
it('should clear timeout', () => {
jest.useFakeTimers();
const mockTimerValue = 12345;
setTimeout.mockReturnValue(mockTimerValue);
const wrapper = mount(
<LoadingIndicator isLoading={true}>
<div>ahoy!</div>
@bruceharris
bruceharris / LoadingIndicator.js
Created Mar 2, 2018
React Unit Testing Example 17
View LoadingIndicator.js
componentWillUnmount() {
clearTimeout();
}
@bruceharris
bruceharris / LoadingIndicator.js
Created Mar 2, 2018
React Unit Testing Example 16
View LoadingIndicator.js
componentWillUnmount() {
clearTimeout(this._delayTimer);
}
@bruceharris
bruceharris / LoadingIndicator.test.js
Created Mar 2, 2018
React Unit Testing Example 15
View LoadingIndicator.test.js
describe('on unmount', () => {
it('should clear timeout', () => {
jest.useFakeTimers();
const wrapper = mount(
<LoadingIndicator isLoading={true}>
<div>ahoy!</div>
</LoadingIndicator>
);
wrapper.unmount();
@bruceharris
bruceharris / LoadingIndicator.js
Created Mar 2, 2018
React Unit Testing Example 14
View LoadingIndicator.js
componentDidMount () {
this._delayTimer = setTimeout(
() => this.setState({ isPastDelay: true }), 200
);
}
@bruceharris
bruceharris / LoadingIndicator.test.js
Created Mar 2, 2018
React Unit Testing Example 13
View LoadingIndicator.test.js
describe('when isLoading is true', () => {
describe('given 200ms have elapsed', () => {
it('should render loading indicator', () => {
jest.useFakeTimers();
const wrapper = mount(
<LoadingIndicator isLoading={true}>
<div>ahoy!</div>
</LoadingIndicator>
);
@bruceharris
bruceharris / LoadingIndicator.js
Last active Mar 2, 2018
React Unit Testing Example 12
View LoadingIndicator.js
componentDidMount () {
this._delayTimer = setTimeout(
() => this.setState({ isPastDelay: true }), 100
);
}
@bruceharris
bruceharris / LoadingIndicator.js
Last active Mar 2, 2018
React Unit Testing Example 11
View LoadingIndicator.js
export default class LoadingIndicator extends Component {
static propTypes = {
isLoading: PropTypes.bool.isRequired,
};
state = {
isPastDelay: false
};
componentDidMount () {
@bruceharris
bruceharris / LoadingIndicator.js
Created Mar 2, 2018
React Unit Testing Example 10
View LoadingIndicator.js
render() {
if (this.props.isLoading) {
if (!this.state.isPastDelay) {
return null;
}
return <div>loading...</div>;
}
return this.props.children;
}
You can’t perform that action at this time.