【发布时间】:2018-01-15 07:28:03
【问题描述】:
我的 LoadingIndicator 测试文件中有以下代码。我正在使用 JEST + Enzyme 来测试 LoadingIndicator 容器类。
我一直在努力将分支覆盖率提高到 100%。它卡在 91% 上。我无法涵盖的分支是 LoadingIndicator 容器类中的 if (!this.timeoutID)。请帮助我了解我在这里缺少什么。
import ...;
import ConnectedLoadingIndicator,{ LoadingIndicator } from './loadingIndicator';
jest.useFakeTimers();
describe('LoadingIndicator unconnected container component', () => {
let wrapper;
let instance;
beforeEach(() => {
wrapper = shallow(<LoadingIndicator
loading='true'
error='false' />);
instance = wrapper.instance();
});
it('checks loadingIndicator is hidden on loading false', () => {
wrapper.setProps({ loading: false, error: false });
expect(instance.state.showIndicator).toBe(false);
expect(wrapper.find('.loading-hidden').length).toEqual(1);
});
it('checks loadingIndicator is shown after timer runs', () => {
wrapper.setProps({ loading: true, error: false });
jest.runOnlyPendingTimers();
expect(instance.state.showIndicator).toBe(true);
expect(wrapper.find('.loading-show').length).toEqual(1);
});
it('checks loadingIndicator is hidden on error true', () => {
wrapper.setProps({ loading: true, error: true });
expect(instance.state.showIndicator).toBe(false);
expect(wrapper.find('.loading-hidden').length).toEqual(1);
});
it('checks destroyTimer behavior on loading false and error false', () => {
wrapper.setProps({ loading: false, error: false });
expect(instance.timeoutID).toBe(null);
expect(instance.state.showIndicator).toBe(false);
});
});
LoadingIndicator 容器类
import ...;
import LoadingIndicatorComponent from '../../../../components/loadingIndicator';
export class LoadingIndicator extends Component {
constructor(props) {
super(props);
this.timeoutID = null;
this.state = {
showIndicator: false,
};
}
componentDidMount() {
this.ensureTimer(this.props);
}
componentWillUnmount() {
this.destroyTimer();
}
componentWillReceiveProps(props) {
if (props.loading !== this.props.loading
|| props.error !== this.props.error) {
this.ensureTimer(props);
}
}
ensureTimer(props) {
if (props.loading && !props.error) {
if (!this.timeoutID) {
this.timeoutID = setTimeout(() => {
this.timeoutID = null;
this.setState({ showIndicator: true });
}, props.timeoutPeriod);
}
} else {
this.destroyTimer();
}
}
destroyTimer() {
clearTimeout(this.timeoutID);
this.timeoutID = null;
this.setState({ showIndicator: false });
}
render() {
console.log(this.state.showIndicator);
return (
<div className =
{`${this.state.showIndicator ? 'loading-show' : 'loading-hidden'}`}>
<LoadingIndicatorComponent>
Loading...
</LoadingIndicatorComponent>
</div>
);
}
}
const mapStateToProps = (state) => ({
loading: isLoading(state),
error: hasError(state),
});
// timeoutPeriod of 1000 is for showing loading indicator after 1000ms
LoadingIndicator.defaultProps = {
timeoutPeriod: 1000,
};
export default connect(mapStateToProps)(LoadingIndicator);
【问题讨论】:
标签: javascript reactjs react-redux jestjs enzyme