I am using tape, enzyme, jsdom and sinon for my testing purposes. I wanna test the simple thing, that the state was changed after calling the method.
class Countdown extends Component {
state = {
count: 0,
countdownStatus: 'stopped'
}
componentDidUpdate = (prevProps, prevState) => {
if (this.state.countdownStatus !== prevState.countdownStatus) {
switch (this.state.countdownStatus) {
case 'started':
this.startTimer()
break
}
}
}
startTimer = () => {
this.timer = setInterval(() => {
const newCount = this.state.count - 1
this.setState({
count: newCount >= 0 ? newCount : 0
})
}, 1000)
}
handleSetCountdown = (seconds) => {
this.setState({
count: seconds,
countdownStatus: 'started'
})
}
render () {
const {count} = this.state
return (
<div>
<Clock totalSeconds={count} />
<CountdownForm onSetCountdown={this.handleSetCountdown} />
</div>
)
}
}
export default Countdown
And this is not working. It says that it passes but then my last test always hangs for some reason, all test passes but they don't exit. Maybe it is because of setInterval although I don't test it.
test('Countdown => should set state to 10, (t) => {
t.plan(1)
const wrapper = shallow(<Countdown />)
wrapper.instance().handleSetCountdown(10)
wrapper.update()
t.equal(wrapper.state().count, 10)
})
EDIT: Ok, i figured it down. The tests are not ending because of setInterval. How would I fix this?
EDIT 2: The solution was pretty simple. I just added
var clock = sinon.useFakeTimers()
and all test finish like they should.
Answer to this problem was simple. Using sinon fake timers sinonjs.org/releases/v2.2.0/fake-timers Causes Sinon to replace the global setTimeout so tests can finish
test('Countdown => should set state to 10', (t: Object) => {
t.plan(1)
const wrapper: Object = shallow(<Countdown />)
/* Causes Sinon to replace the global setTimeout so tests can finish */
const clock = sinon.useFakeTimers()
const instance = wrapper.instance()
instance.handleSetCountdown(10)
t.equal(wrapper.state().count, 10)
})
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments