83 lines
2.7 KiB
TypeScript
83 lines
2.7 KiB
TypeScript
import { SELF } from 'cloudflare:test';
|
|
import { describe, it, expect } from 'vitest';
|
|
|
|
describe('tangfamily API', () => {
|
|
describe('POST /api/login', () => {
|
|
it('rejects wrong visitor password', async () => {
|
|
const res = await SELF.fetch('http://example.com/api/login', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ password: 'wrongpass', isAdmin: false }),
|
|
});
|
|
expect(res.status).toBe(401);
|
|
const data = await res.json() as { success: boolean };
|
|
expect(data.success).toBe(false);
|
|
});
|
|
|
|
it('accepts correct visitor password', async () => {
|
|
const res = await SELF.fetch('http://example.com/api/login', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ password: 'tangfamily', isAdmin: false }),
|
|
});
|
|
expect(res.status).toBe(200);
|
|
const data = await res.json() as { success: boolean; token: string };
|
|
expect(data.success).toBe(true);
|
|
expect(typeof data.token).toBe('string');
|
|
});
|
|
|
|
it('rejects wrong admin password', async () => {
|
|
const res = await SELF.fetch('http://example.com/api/login', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ password: 'wrongpass', isAdmin: true }),
|
|
});
|
|
expect(res.status).toBe(401);
|
|
});
|
|
|
|
it('accepts correct admin password', async () => {
|
|
const res = await SELF.fetch('http://example.com/api/login', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ password: 'shumengya5201314', isAdmin: true }),
|
|
});
|
|
expect(res.status).toBe(200);
|
|
const data = await res.json() as { success: boolean; isAdmin: boolean };
|
|
expect(data.success).toBe(true);
|
|
expect(data.isAdmin).toBe(true);
|
|
});
|
|
});
|
|
|
|
describe('GET /api/members', () => {
|
|
it('returns 401 without token', async () => {
|
|
const res = await SELF.fetch('http://example.com/api/members');
|
|
expect(res.status).toBe(401);
|
|
});
|
|
|
|
it('returns member list with valid token', async () => {
|
|
// login first
|
|
const loginRes = await SELF.fetch('http://example.com/api/login', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ password: 'tangfamily', isAdmin: false }),
|
|
});
|
|
const { token } = await loginRes.json() as { token: string };
|
|
|
|
const res = await SELF.fetch('http://example.com/api/members', {
|
|
headers: { Authorization: `Bearer ${token}` },
|
|
});
|
|
expect(res.status).toBe(200);
|
|
const data = await res.json();
|
|
expect(Array.isArray(data)).toBe(true);
|
|
});
|
|
});
|
|
|
|
describe('unknown routes', () => {
|
|
it('returns 404 for unknown API route', async () => {
|
|
const res = await SELF.fetch('http://example.com/api/unknown');
|
|
expect(res.status).toBe(404);
|
|
});
|
|
});
|
|
});
|
|
|