I have this React Component
export class Timer extends Component {
constructor(props) {
super(props);
this.state = {i : props.i};
}
componentDidMount(){
this.decrementCounter();
}
decrementCounter(){
if(this.state.i < 1){
return;
}
setTimeout(() => {
this.setState({i : this.state.i - 1})
this.decrementCounter()}, 1000);
}
render(){
return <span>{this.state.i}</span>
}}
And I want to express a test like this
jest.useFakeTimers();
it('should decrement timer ', () => {
const wrapper = shallow(<Timer i={10} />);
expect(wrapper.text()).toBe("10");
jest.runOnlyPendingTimers();
expect(wrapper.text()).toBe("9");
});
currently the first expect pass but the second fails
Expected value to be (using ===):
"9"
Received:
"10"
How can I properly test this component ?
Use Full Rendering API, mount(...)
You can use
mount()
instead ofshallow()
likeOr you can pass additional object to
shallow
to instrument it to run lifecycle methodsI tested it. It works.