• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

SyTW2223 / E01 / 3976491236

pending completion
3976491236

push

github

juanmdom
test y responsividad

18 of 66 branches covered (27.27%)

Branch coverage included in aggregate %.

7 of 12 new or added lines in 5 files covered. (58.33%)

211 of 408 relevant lines covered (51.72%)

1.31 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

23.71
/client/src/components/form/SessionForm.jsx
1
import React, { useState } from 'react';
2
import { TextField,
3
         Button,
4
         Box,
5
         Container,
6
         Alert, 
7
         ThemeProvider} from '@mui/material';
8
import ObjectiveForm from './ObjectiveForm';
9
import { useDispatch } from 'react-redux';
10
import DoneAllIcon from '@mui/icons-material/DoneAll';
11
import { theme } from '../../themes/mainTheme';
12
import { useSelector } from 'react-redux';
13
import { selectUser } from '../../features/userSlice';
14

15
const SessionForm = () => {
2✔
16
  const [session, setSession] = useState('');
6✔
17
  const [objectives, setObjectives] = useState([]);
6✔
18
  const [openAlert, setAlert] = useState(false);
6✔
19
  const [openSuccess, setSuccess] = useState(false);
6✔
20

21
  const user = useSelector(selectUser);
6✔
22
  const username = user && user.userName;
6!
23
  const token = user && user.token;
6!
24

25
  const dispatch = useDispatch();
6✔
26

27
  const handleAddObjective = () => {
6✔
28
    setObjectives([...objectives, { name: '', tasks: [], completed: false }]);
×
29
  }
30

31
  const handleAddTask = (index) => {
6✔
32
    const newObjectives = [...objectives];
×
33
    newObjectives[index].tasks.push('');
×
34
    setObjectives(newObjectives);
×
35
  }
36

37
  const handleObjectiveChange = (event, index) => {
6✔
38
    const newObjectives = [...objectives];
×
39
    newObjectives[index].name = event.target.value;
×
40
    setObjectives(newObjectives);
×
41
  }
42

43
  const handleTaskChange = (event, objectiveIndex, taskIndex) => {
6✔
44
    const newObjectives = [...objectives];
×
45
    newObjectives[objectiveIndex].tasks[taskIndex] = event.target.value;
×
46
    setObjectives(newObjectives);
×
47
  }
48

49
  const handleCompleteSession = async (e) => {
6✔
50
    let emptyField = false;
×
51
    objectives.forEach((objective) => {
×
52
      if (!objective.name) {
×
53
        emptyField = true;
×
54
      }
55
      objective.tasks.forEach((task) => {
×
56
        if (!task) {
×
57
          emptyField = true;
×
58
        }
59
      });
60
    });
61

62
    if (emptyField) {
×
63
      setAlert(true);
×
64
      return;
×
65
    } else {
66
      // Hacemos un GET para tener el usuario guardado en la base de datos ya que necesitamos su _id.
67
      let url = `http://localhost:4000/user/?token=${token}&name=${username}`;
×
68
      let realUser = await fetch(url)
×
69
      realUser = await realUser.json()
×
70

71
      // Ahora haremos un POST de la session con la id del usuario.
72
      let options = {
×
73
        method: "POST", body: new URLSearchParams({
74
          'name': session,
75
          'user': realUser._id,
76
          'token': token,
77
        })
78
      };
79
      url = `http://localhost:4000/session/`;
×
80
      await fetch(url, options);
×
81

82
      // Ahora tenemos que obtener la id de la session que creamos en la base de datos, para ello primero haremos un get
83
      url = `http://localhost:4000/session/?token=${token}&name=${session}&user=${realUser._id}`;
×
84
      let realSession = await fetch(url);
×
85
      realSession = await realSession.json();
×
86
      // Este Get devuelve un array con las sesiones que coincidan, en caso de que un usuario tenga varias sesiones con el mismo nombre
87
      // la actual se encontrará en la ultima posicion del array ya que se devuelven en orden por lo que siempre nos quedaremos con el ultimo elemento del array..
88
      realSession = realSession[realSession.length - 1];
×
89
      // Ahora que tenemos la session actual que queremos guardar, con su ID podemos hacer el POST de los objetivos.
90
      objectives.forEach(async (element) => {
×
91
        // Posteamos objetivos con las id de la sesion correspondiente
92
        url = `http://localhost:4000/objective/`;
×
93
        options = {
×
94
          method: "POST", body: new URLSearchParams({
95
            'name': element.name,
96
            'session': realSession._id,
97
            'token': token,
98
          })
99
        };
100
        await fetch(url, options);
×
101
        // Ahora tenemos que hacer un POST de las tareas correspondientes a cada object, para esto lo que haremos será un GET teniendo en cuenta
102
        // nuevamente que nos quedamos con el ultimo objetivo que será el actual.
103
        url = `http://localhost:4000/objective/?token=${token}&name=${element.name}&session=${realSession._id}`;
×
104
        let realObjective = await fetch(url);        
×
105
        realObjective = await realObjective.json()
×
106
        // Nos quedaremos con el ultimo objetivo añadido que es el que nos interesa porque iremos iterando uno a uno.
107
        realObjective = realObjective[realObjective.length-1]
×
108
        // Ahora podemos hacer un POST de las tareas teniendo nuestro objetivo de interés.
109
        element.tasks.forEach( async(element) => {
×
110
          url = `http://localhost:4000/task/`;
×
111
          options = {
×
112
            method: "POST", body: new URLSearchParams({
113
              'name': element,
114
              'objective': realObjective._id,
115
              'token': token,
116
            })
117
          };
118
          await fetch(url, options);
×
119
        });
120
      });
121
      setAlert(false);
×
122
      setSuccess(true);
×
123
      setObjectives([]);
×
124
      setSession('');
×
125
    }
126

127
  }
128

129
  const handleCompleteObjective = (index) => {
6✔
130
    const newObjectives = [...objectives];
×
131
    newObjectives[index].completed = true;
×
132
    setObjectives(newObjectives);
×
133
  }
134

135
  const handleDeleteTask = (objectiveIndex, taskIndex) => {
6✔
136
    const newObjectives = [...objectives];
×
137
    newObjectives[objectiveIndex].tasks.splice(taskIndex, 1);
×
138
    setObjectives(newObjectives);
×
139
  }
140

141
  const handleDeleteObjective = (objectiveIndex) => {
6✔
142
    const newObjectives = [...objectives];
×
143
    newObjectives.splice(objectiveIndex, 1);
×
144
    setObjectives(newObjectives);
×
145
  }
146

147
  const useStyles = {
6✔
148
    bgcolor: theme.palette.primary.main,
149
    boxShadow: 4,
150
    borderRadius: 2
151
  }
152

153
  return (
6✔
154
    <ThemeProvider theme={theme}>      
155
      <Container sx={useStyles}>
156
        {openAlert && <Alert severity="error" onClose={() => setAlert(false)}>¡Rellena <strong> TODOS </strong> los campos!</Alert>}
×
157
        {openSuccess && <Alert severity="success" onClose={() => setSuccess(false)}>¡Todo ha ido perfecto!</Alert>}
×
158
        {/* Session form */}
159
        <TextField
160
          data-testid="add-session-input"
161
          required
162
          variant='filled'
163
          label="Session Name"
164
          fullWidth
165
          value={session}
166
          onChange={(event) => setSession(event.target.value)}
×
167
          sx={{
168
            bgcolor: 'primary.secondary',
169
            marginTop: 2,
170
            borderRadius: 1,
171
            
172
          }}
173
        />
174
        <Button onClick={handleAddObjective} data-testid="add-session-btn"
175
                sx={{bgcolor: 'primary.secondary', marginTop: 1, marginBottom: 1,
176
          '&:hover': {
177
            color: 'secondary.secondary',
178
          }}}
179
        >
180
          Add</Button>
181
        <Button
182
          data-testid="complete-session-btn" 
183
          sx={{
184
            borderRadius: 5,
185
            bgcolor: 'primary.secondary',
186
            marginX: 2,
187
            '&:hover': {
188
              color: 'secondary.secondary',
189
            }
190
          }}
191
          onClick={(e) => { 
192
            if (session.length === 0) {
×
193
              setAlert(true)
×
194
            } else {
195
              handleCompleteSession(e)}
×
196
          }}
197
        >
198
          <DoneAllIcon/>
199
        </Button>
200
        
201
        {/* Objetive Form */}
202
        <Box data-testid="objectives-form">
203
            {objectives.map((objective, index) => (
NEW
204
             <ObjectiveForm 
×
205
              objective={objective}
206
              objectiveIndex={index} 
207
              handleTaskChange={handleTaskChange}
208
              handleDeleteTask={handleDeleteTask}
209
              handleObjectiveChange={handleObjectiveChange}
210
              handleAddTask={handleAddTask}
211
              handleCompleteObjective={handleCompleteObjective}
212
              handleDeleteObjective={handleDeleteObjective}
213
            />
214
            ))}
215
        </Box>
216

217
      </Container>
218
    </ThemeProvider>
219
  );
220
}
221

222
export default SessionForm;
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc