admin管理员组文章数量:1331230
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} />
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} />
After the useEffect will run the state should be false
. Now i want to test the ponent 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()
})
})
})
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?
-
Set initial value true
const [state, setState] = useState(true);
– Asif vora Commented Nov 3, 2021 at 7:07 -
@Asifvora, if i set that, on the first render i get
true
and on the secondfalse
, but i need to use onlyfalse
, so to wait after useEffect will run. – Asking Commented Nov 3, 2021 at 7:12
2 Answers
Reset to default 3You need to wait until the ponent did mount and then run your expectation. In react testing library, there is a special method for it. waitFor
.
from React testing library documentation:
When in need to wait for any period of time you can use waitFor, to wait for your expectations to pass.
import {waitFor} from '@testing-library/react'
describe('App', () => {
// rest of the codes ...
test('It should render the correct value', async() => {
const v = utils.queryByText(12)
await waitFor(() => {
expect(v).toBeInTheDocument()
})
})
})
})
You are getting two console logs because this line initialises your state (undefined
):
const [state, setState] = useState();
After that the useEffect
hook runs onComponentDidMount
and changes the state, which causes the ponent to rerender (second log statement).
You could use something like this, if you want to init the state from the props
:
const [state, setState] = useState(!data);
Update:
This works on my machine:
Maybe you have some typos?
本文标签: javascriptTest the changed state after useEffect has runnedStack Overflow
版权声明:本文标题:javascript - Test the changed state after useEffect has runned - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742260871a2442488.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论