eletrotupi / tcc/ api/tests/users/create.test.tsd056c177d3c92fbe121ee526d7bab29f7ba377eb
2.1 KB | 66 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, expectPublicUser } 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', acceptedTerms: true } })
22

23
    expect(res.status).toBe(201)
24
    expect(res.body.token).toBeTruthy()
25
    expect(res.body.user.email).toBe('new@example.com')
26
    expect(res.body.user.active).toBe(false)
27
    expectPublicUser(res.body.user)
28

29
    const dbUser = await db.user.findUnique({ where: { email: 'new@example.com' } })
30
    expect(dbUser).not.toBeNull()
31
    expect(dbUser!.firstName).toBe('Novo')
32
    expect(dbUser!.activationCode).toMatch(/^\d{6}$/)
33
    expect(dbUser!.termsAcceptedAt).not.toBeNull()
34
    expect(dbUser!.termsVersion).toBe('1')
35

36
    expect(recordedJobs).toContainEqual(
37
      expect.objectContaining({
38
        queue: 'mail',
39
        name: 'mail:welcome',
40
        data: { userId: dbUser!.id, code: dbUser!.activationCode },
41
      })
42
    )
43
  })
44

45
  it('returns 409 for duplicate email', async () => {
46
    await db.user.create({
47
      data: { email: 'dup@example.com', firstName: 'A', encryptedPassword: 'x' },
48
    })
49

50
    const res = await request(app)
51
      .post('/users')
52
      .send({ user: { email: 'dup@example.com', firstName: 'B', password: 'senha123', acceptedTerms: true } })
53

54
    expect(res.status).toBe(409)
55
  })
56

57
  it('returns 400 for missing required fields', async () => {
58
    const res = await request(app)
59
      .post('/users')
60
      .send({ user: { email: 'x@example.com' } })
61

62
    expect(res.status).toBe(400)
63
    expect(res.body.error).toBeTruthy()
64
    expect(res.body.fields).toBeTruthy()
65
  })
66
})