1
0
Files
record-shop/server/test/authRoutes.test.ts

75 lines
2.3 KiB
TypeScript
Raw Normal View History

import { describe, it, expect } from 'vitest'
import { buildTestApp, setupAdmin, getCookie, auth } from './helpers.js'
describe('auth routes', () => {
it('setup creates admin when no users exist, then is closed', async () => {
const app = await buildTestApp()
const status = await app.inject({ method: 'GET', url: '/api/setup' })
expect(status.json()).toEqual({ needed: true })
const cookie = await setupAdmin(app)
const me = await app.inject({ method: 'GET', url: '/api/me', ...auth(cookie) })
expect(me.statusCode).toBe(200)
expect(me.json()).toEqual({ user: { id: 1, username: 'admin', isAdmin: true } })
const again = await app.inject({
method: 'POST',
url: '/api/setup',
payload: { username: 'x', password: 'password123' },
})
expect(again.statusCode).toBe(403)
await app.close()
})
it('setup validates input', async () => {
const app = await buildTestApp()
const bad = await app.inject({
method: 'POST',
url: '/api/setup',
payload: { username: 'ab', password: 'short' },
})
expect(bad.statusCode).toBe(400)
await app.close()
})
it('login and logout', async () => {
const app = await buildTestApp()
await setupAdmin(app)
const login = await app.inject({
method: 'POST',
url: '/api/login',
payload: { username: 'admin', password: 'adminpass123' },
})
expect(login.statusCode).toBe(200)
const cookie = getCookie(login)
const me = await app.inject({ method: 'GET', url: '/api/me', ...auth(cookie) })
expect(me.statusCode).toBe(200)
await app.inject({ method: 'POST', url: '/api/logout', ...auth(cookie) })
const after = await app.inject({ method: 'GET', url: '/api/me', ...auth(cookie) })
expect(after.statusCode).toBe(401)
await app.close()
})
it('login rejects wrong password', async () => {
const app = await buildTestApp()
await setupAdmin(app)
const res = await app.inject({
method: 'POST',
url: '/api/login',
payload: { username: 'admin', password: 'wrongpass123' },
})
expect(res.statusCode).toBe(401)
await app.close()
})
it('protected route requires auth', async () => {
const app = await buildTestApp()
const res = await app.inject({ method: 'GET', url: '/api/me' })
expect(res.statusCode).toBe(401)
await app.close()
})
})