Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
468 views
in Technique[技术] by (71.8m points)

reactjs - Jest: Testing React state change in useEffect

I am new at Jest and Enzyme, and am struggling to write a unit test to check if my component renders correctly when a certain state value exists.

Below is my code:

//Auth.js
export const Auth = ({ children }) => {
    const [authStatus, setAuthStatus] = useState('waiting')

    useEffect(()=>{
       const status = await getAuth()
       if (status) {
           setAuthStatus('Authed')
       }
       else{
           setAuthStatus('Unauthed')
       }
    },[])

    return (
       <>
          {authStatus === 'waiting' && <p>Loading...</p>}
          {authStatus === 'Authed' && <>{Children}</>
       </>
    )
}

In the above code, I wanted to test the Loading state when authStatus is default and I wanted to write a second test to test if the Children being passed in props are rendered when authStatus is Authed. I found a way to mock implement the state change, but that implementation is restricted to only one useEffect, as there may be multiple useEffects in the future, I do not want to go with this approach. Is there any better way to test this behavior?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

first, you can't just use await keyword in useEffect callback, it should be an async function which would do that like this:

//Auth.js
export const Auth = ({ children }) => {
    const [authStatus, setAuthStatus] = useState('waiting')

    async function checkAuth(){
       const status = await getAuth()
       if (status) {
           setAuthStatus('Authed')
       }
       else{
           setAuthStatus('Unauthed')
       }
    }

    useEffect(()=>{
       checkAuth();
    },[])

    return (
       <>
          {authStatus === 'waiting' && <p>Loading...</p>}
          {authStatus === 'Authed' && <>{Children}</>
       </>
    )
}

and then it's a best practice not to test implementation details like state.

usually, you want to mock api calls and imported modules like getAuth function.

so I think you should mock the getAuth function and then return your desired value in your mock so you can test if differnet state like loading will happen or not


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...