Reputation: 35
This is my react component (used for learning testing-library):
import '@babel/polyfill';
import React, {useState} from 'react'
import { render, cleanup, fireEvent, waitFor, getByTestId, getByText} from "@testing-library/react";
import '@testing-library/jest-dom'
const FirstTest = () =>{
const [counter, setCounter] = useState(0)
const delayFunc = ()=>{
setTimeout(()=>{
setCounter(counter+1)
}, 5000)
}
return (
<div>
<h1 data-testid="h1counter">{counter}</h1>
<button data-testid="buttonAdd" onClick={delayFunc}>+</button>
<button
disabled
data-testid="buttonDown"
onClick={()=> setCounter(counter-1)}
>-</button>
</div>
)
}
and this is my test code:
afterEach(cleanup)
it('delay counter', async() =>{
const { getByTestId } = render(<FirstTest />)
fireEvent.click(getByTestId('buttonAdd'))
await waitFor(()=> {
expect((getByTestId("h1counter")).textContent).toBe("1")
})
})
My question is why waitFor
doesn't seem to work because the result received : "0"?
Upvotes: 3
Views: 5767
Reputation: 50418
This happens because the default timeout for waitFor
is 1000ms, while your state change only happens 5000ms after the click event.
You could either reduce the setTimeout
delay and/or increase waitFor
timeout, but a better solution would be to mock the timers using jest.useFakeTimers()
during your test.
Upvotes: 3