I use ReactJs
, jest and react testing library. I have this code:
const App = ({data}) => {
const [state, setState] = useState(); // after useEffect runs state should be false
console.log('test state', state)
useEffect(() => {
setState(!data)
}, [])
return <p>'data is' {data},<p/>
}
<App data={12} />
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
After the useEffect
will run the state
should be false
. Now i want to test the component using jest and react testing library.
describe('App', () => {
beforeEach(() => {
const setValue = jest.fn(x => {});
React.useState = jest.fn()
.mockImplementationOnce(x => [x, setValue])
})
test('It should render the correct value', async() => {
const v = utils.queryByText(12)
expect(v).toBeInTheDocument()
})
})
})
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
When i run the test in console.log('test state', state)
i get for first time console.log('test state', undefined)
and after that console.log('test state', false)
, but i need to get only the false
value, because due the fact that for the first time the value is undefined
the test fails. How to do this?
CodePudding user response:
You need to wait until the component did mount and then run your expectation. In react testing library, there is a special method for it. waitFor
.
Maybe you have some typos?