我如何在setState回调参数中测试所有这些逻辑 [英] How can I test all this logic inside setState callback parameter

查看:62
本文介绍了我如何在setState回调参数中测试所有这些逻辑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试测试以下代码.我正在使用玩笑和反应测试库.这是我这样使用setState的第一个时间.我解决了最初的问题,这是为了避免传入当前状态的依赖关系,但是我不确定如何测试这一点.有人可以请教吗.

  useEffect(()=> {setUsers(currentUsers => {if(currentUsers ===未定义){返回userDataFromApi;} 别的 {//用户已经存在const mergedUserData = currentUsers.map(existingUser => {const matchedUser = userDataFromApi.find(user => user.name === existingUser.name);如果(matchedUser){existingUser.stats = user.stats;}返回现有用户;});返回mergedUserData;}});},[setUsers,userDataFromApi]); 

解决方案

这段代码是实现细节.React测试库强制执行UI测试.您可以阅读肯特·多德斯(Kent Dodds)的这篇文章.

在测试中,您可以执行与用户相同的操作(填写表格,单击等等),然后检查用户应该看到或看不到的内容(可能是他的姓名,统计信息等)./p>

如果您从后端获取数据并且只想测试前端,则可以模拟后端的答案.

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]);

解决方案

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.

这篇关于我如何在setState回调参数中测试所有这些逻辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆