eletrotupi / tcc/ api/tests/users/profile.test.js56ae9d8272c35d408c95fb441f727bf93b0507d3
6.4 KB | 246 lines Raw
1
import test from "ava";
2
import request from "supertest";
3
import { createApp } from "../../src/create-app.js";
4
import { setupTestDb, cleanupTestDb } from "../test-helper.js";
5

6
let app;
7
let db;
8
let userId;
9

10
test.before(() => {
11
  db = setupTestDb();
12
  app = createApp(db);
13
});
14

15
let testEmail;
16

17
test.serial.beforeEach(async () => {
18
  cleanupTestDb();
19

20
  // Create a test user with unique email
21
  testEmail = `perfil_${Date.now()}_${Math.random()}@example.com`;
22
  const res = await request(app)
23
    .post("/users")
24
    .send({
25
      email: testEmail,
26
      password: "senha123",
27
      first_name: "Perfil",
28
      last_name: "Teste",
29
      timezone: "America/Sao_Paulo"
30
    });
31

32
  if (res.status !== 201) {
33
    throw new Error(`Failed to create test user: ${JSON.stringify(res.body)}`);
34
  }
35

36
  userId = res.body.id;
37
});
38

39
test.serial("Obter perfil de usuário existente", async (t) => {
40
  const res = await request(app).get(`/users/${userId}`);
41

42
  t.is(res.status, 200);
43
  t.is(Number(res.body.id), Number(userId));
44
  t.is(res.body.email, testEmail);
45
  t.is(res.body.first_name, "Perfil");
46
  t.is(res.body.last_name, "Teste");
47
  t.is(res.body.timezone, "America/Sao_Paulo");
48
  t.truthy(res.body.created_at);
49
  t.truthy(res.body.updated_at);
50
  t.is(typeof res.body.total_moods, 'number');
51
  t.falsy(res.body.password); // Should not include password
52
});
53

54
test.serial("Perfil deve incluir contagem de registros de humor", async (t) => {
55
  // Add some moods
56
  const now = new Date().toISOString();
57

58
  await db.prepare(`
59
    INSERT INTO mood (user_id, rating, stress_level, anxiety_level, energy_level, recorded_at)
60
    VALUES (?, ?, ?, ?, ?, ?)
61
  `).run(userId, 7, 3, 4, 8, now);
62

63
  await db.prepare(`
64
    INSERT INTO mood (user_id, rating, stress_level, anxiety_level, energy_level, recorded_at)
65
    VALUES (?, ?, ?, ?, ?, ?)
66
  `).run(userId, 5, 6, 7, 4, now);
67

68
  const res = await request(app).get(`/users/${userId}`);
69

70
  t.is(res.status, 200);
71
  t.is(res.body.total_moods, 2);
72
});
73

74
test.serial("Falha ao obter perfil de usuário inexistente", async (t) => {
75
  const res = await request(app).get("/users/99999");
76

77
  t.is(res.status, 404);
78
  t.is(res.body.error, "Usuário não encontrado");
79
});
80

81
test.serial("Atualizar email do usuário", async (t) => {
82
  const res = await request(app)
83
    .put(`/users/${userId}`)
84
    .send({
85
      email: "novoemail@example.com"
86
    });
87

88
  t.is(res.status, 200);
89
  t.true(res.body.success);
90

91
  // Verify update
92
  const user = db.prepare("SELECT email FROM users WHERE id = ?").get(userId);
93
  t.is(user.email, "novoemail@example.com");
94
});
95

96
test.serial("Atualizar senha do usuário", async (t) => {
97
  const res = await request(app)
98
    .put(`/users/${userId}`)
99
    .send({
100
      password: "novasenha123"
101
    });
102

103
  t.is(res.status, 200);
104
  t.true(res.body.success);
105

106
  // Verify can login with new password
107
  const loginRes = await request(app)
108
    .post("/users/login")
109
    .send({
110
      email: testEmail,
111
      password: "novasenha123"
112
    });
113

114
  t.is(loginRes.status, 200);
115
});
116

117
test.serial("Atualizar múltiplos campos do usuário", async (t) => {
118
  const res = await request(app)
119
    .put(`/users/${userId}`)
120
    .send({
121
      first_name: "NovoNome",
122
      last_name: "NovoSobrenome",
123
      timezone: "Europe/London"
124
    });
125

126
  t.is(res.status, 200);
127
  t.true(res.body.success);
128

129
  // Verify updates
130
  const user = db.prepare("SELECT * FROM users WHERE id = ?").get(userId);
131
  t.is(user.first_name, "NovoNome");
132
  t.is(user.last_name, "NovoSobrenome");
133
  t.is(user.timezone, "Europe/London");
134
});
135

136
test.serial("Falha ao atualizar com email inválido", async (t) => {
137
  const res = await request(app)
138
    .put(`/users/${userId}`)
139
    .send({
140
      email: "emailinvalido"
141
    });
142

143
  t.is(res.status, 400);
144
  t.is(res.body.error, "Email inválido");
145
});
146

147
test.serial("Falha ao atualizar com senha muito curta", async (t) => {
148
  const res = await request(app)
149
    .put(`/users/${userId}`)
150
    .send({
151
      password: "123"
152
    });
153

154
  t.is(res.status, 400);
155
  t.is(res.body.error, "Senha deve ter pelo menos 6 caracteres");
156
});
157

158
test.serial("Falha ao atualizar email para um já existente", async (t) => {
159
  // Create another user
160
  await request(app)
161
    .post("/users")
162
    .send({
163
      email: "outro@example.com",
164
      password: "senha123",
165
      first_name: "Outro",
166
      last_name: "Usuario"
167
    });
168

169
  // Try to update to existing email
170
  const res = await request(app)
171
    .put(`/users/${userId}`)
172
    .send({
173
      email: "outro@example.com"
174
    });
175

176
  t.is(res.status, 400);
177
  t.is(res.body.error, "Email já está em uso");
178
});
179

180
test.serial("Falha ao atualizar usuário inexistente", async (t) => {
181
  const res = await request(app)
182
    .put("/users/99999")
183
    .send({
184
      first_name: "Novo"
185
    });
186

187
  t.is(res.status, 404);
188
  t.is(res.body.error, "Usuário não encontrado");
189
});
190

191
test.serial("Falha ao atualizar sem campos", async (t) => {
192
  const res = await request(app)
193
    .put(`/users/${userId}`)
194
    .send({});
195

196
  t.is(res.status, 400);
197
  t.is(res.body.error, "Nenhum campo para atualizar");
198
});
199

200
test.serial("Deletar usuário existente", async (t) => {
201
  const res = await request(app).delete(`/users/${userId}`);
202

203
  t.is(res.status, 200);
204
  t.true(res.body.success);
205
  t.is(Number(res.body.deleted), Number(userId));
206

207
  // Verify user is deleted
208
  const user = db.prepare("SELECT * FROM users WHERE id = ?").get(userId);
209
  t.falsy(user);
210
});
211

212
test.serial("Deletar usuário deve deletar seus registros de humores (em cascata)", async (t) => {
213
  // Add a mood
214
  const now = new Date().toISOString();
215
  const moodResult = db.prepare(`
216
    INSERT INTO mood (user_id, rating, stress_level, anxiety_level, energy_level, recorded_at)
217
    VALUES (?, ?, ?, ?, ?, ?)
218
  `).run(userId, 7, 3, 4, 8, now);
219

220
  const moodId = moodResult.lastInsertRowid;
221

222
  // Add mood components
223
  db.prepare(`
224
    INSERT INTO mood_components (mood_id, emotion, intensity)
225
    VALUES (?, ?, ?)
226
  `).run(moodId, 'joy', 8);
227

228
  // Delete user
229
  const res = await request(app).delete(`/users/${userId}`);
230
  t.is(res.status, 200);
231

232
  // Verify moods are deleted
233
  const mood = db.prepare("SELECT * FROM mood WHERE user_id = ?").get(userId);
234
  t.falsy(mood);
235

236
  // Verify mood components are deleted
237
  const component = db.prepare("SELECT * FROM mood_components WHERE mood_id = ?").get(moodId);
238
  t.falsy(component);
239
});
240

241
test.serial("Falha ao deletar usuário inexistente", async (t) => {
242
  const res = await request(app).delete("/users/99999");
243

244
  t.is(res.status, 404);
245
  t.is(res.body.error, "Usuário não encontrado");
246
});