[英]testing-library react mock function with callback that will set state on return
I'm new to the testing world, and I'm trying to test a component with useEffect
that will execute a function that gets 3 parameters and the last one is a callback with setMyState
inside:我是测试世界的新手,我正在尝试使用useEffect
测试一个组件,该组件将执行一个获取 3 个参数的 function,最后一个是内部带有setMyState
的回调:
my component:我的组件:
const Component = () => {
const [myState, setMystate] = useState({})
useEffect(() => {
myFunctions('string param>','<string param>', (foo) => {
setMystat(foo)
})
})
}
return...
I'm using '@testing-library/react'
for testing.我正在使用'@testing-library/react'
进行测试。 Not sure how can I render the component in the test then make sure the state got the new state set to it and the component retendered.不知道如何在测试中渲染组件,然后确保 state 设置了新的 state 并重新渲染了组件。
I managed to solved the issue by mocking the model with the function and a callback, and calling the callback function: on the top of the test: I managed to solved the issue by mocking the model with the function and a callback, and calling the callback function: on the top of the test:
jest.mock('../../../path/to/module', () => ({
//function in the module I need to call
myFunction: {
//this will execute the function when called from the "useEffect"
//method inside the function
method : (param1, param2, callback ) => callback({item: 'item'})
},
}) })
component :
const Component = () => {
const [myState, setMystate] = useState({})
useEffect(() => {
myFunctions.post('string param>','<string param>', (foo) => {
setMystat(foo)
})
}) } }) }
return...返回...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.