eletrotupi / tcc/ api/tests/users/create.test.ts5b0a5a6cf15017c93e1dd78af7d46e7eb1c3f262
1.8 KB | 61 lines Raw
1
import { describe, it, expect, afterAll, beforeEach } from 'vitest'
2
import request from 'supertest'
3
import { createApp } from '@app/createApp'
4
import { buildPrisma, cleanupTestDb } from '../test-helper'
5
import { recordedJobs, resetQueueMocks } from '../mocks/queue'
6

7
const app = createApp()
8
const db = buildPrisma()
9

10
afterAll(() => db.$disconnect())
11
beforeEach(async () => {
12
  await cleanupTestDb(db)
13

14
  resetQueueMocks()
15
})
16

17
describe('POST /users', () => {
18
  it('creates a user and returns a JWT token', async () => {
19
    const res = await request(app)
20
      .post('/users')
21
      .send({ user: { email: 'new@example.com', firstName: 'Novo', password: 'senha123' } })
22

23
    expect(res.status).toBe(201)
24
    expect(res.body.token).toBeTruthy()
25

26
    const dbUser = await db.user.findUnique({ where: { email: 'new@example.com' } })
27
    expect(dbUser).not.toBeNull()
28
    expect(dbUser!.firstName).toBe('Novo')
29
    expect(dbUser!.activationCode).toMatch(/^\d{6}$/)
30

31
    expect(recordedJobs).toContainEqual(
32
      expect.objectContaining({
33
        queue: 'mail',
34
        name: 'mail:welcome',
35
        data: { userId: dbUser!.id, code: dbUser!.activationCode },
36
      })
37
    )
38
  })
39

40
  it('returns 409 for duplicate email', async () => {
41
    await db.user.create({
42
      data: { email: 'dup@example.com', firstName: 'A', encryptedPassword: 'x' },
43
    })
44

45
    const res = await request(app)
46
      .post('/users')
47
      .send({ user: { email: 'dup@example.com', firstName: 'B', password: 'senha123' } })
48

49
    expect(res.status).toBe(409)
50
  })
51

52
  it('returns 400 for missing required fields', async () => {
53
    const res = await request(app)
54
      .post('/users')
55
      .send({ user: { email: 'x@example.com' } })
56

57
    expect(res.status).toBe(400)
58
    expect(res.body.error).toBeTruthy()
59
    expect(res.body.fields).toBeTruthy()
60
  })
61
})