Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

reactjs - How can I test all this logic inside setState callback parameter

I'm trying to test the following code. I'm using jest and react testing library. This is the firs time I've used setState like this. I solved my initial which was to avoid passing in the dependency of current state but I'm not sure how can I test this. Can someone please advise.

useEffect(() => {
    setUsers(currentUsers => {
        if(currentUsers === undefined) {
            return userDataFromApi;
        } else {
            //Users already exist in state
            const mergedUserData = currentUsers.map(existingUser => {
                const matchedUser = userDataFromApi.find(user => user.name === existingUser.name);

                if (matchedUser) {
                    existingUser.stats = user.stats;
                }

                return existingUser;
            });

            return mergedUserData;
        }
    });
}, [setUsers, userDataFromApi]);
See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

This piece of code is implementation detail. React testing library enforces UI testing. You can read this article from Kent Dodds.

In your tests you can do the same thing as the user would do (fill a form, click etc.), and then check what the user should see or not see (maybe his name, his stats etc.).

And if you get data from your backend and you would like to test only the frontend, you can mock the answer of the backend.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...