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

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...