not-your-blog-v2/cloudflare-worker/test/upload.test.js
2026-05-05 18:58:52 +03:00

62 lines
1.9 KiB
JavaScript

import { describe, it, expect } from 'vitest';
import { readFileSync } from 'fs';
import { resolve } from 'path';
import { config } from 'dotenv';
config({ path: resolve(__dirname, '../../.env') });
const WORKER_URL = process.env.PUBLIC_WORKER_URL;
const UPLOAD_SECRET = process.env.PUBLIC_UPLOAD_SECRET;
const IMAGE = readFileSync(resolve(__dirname, '../../pictures/image2.png'));
describe('Worker auth', () => {
it('rejects request with no auth header', async () => {
const res = await fetch(`${WORKER_URL}/presign?filename=image2.png`);
expect(res.status).toBe(401);
});
it('rejects request with wrong secret', async () => {
const res = await fetch(`${WORKER_URL}/presign?filename=image2.png`, {
headers: { Authorization: 'Bearer wrong-secret' },
});
expect(res.status).toBe(401);
});
});
describe('Presign endpoint', () => {
it('returns 400 when filename is missing', async () => {
const res = await fetch(`${WORKER_URL}/presign`, {
headers: { Authorization: `Bearer ${UPLOAD_SECRET}` },
});
expect(res.status).toBe(400);
});
it('returns a presigned URL and key', async () => {
const res = await fetch(`${WORKER_URL}/presign?filename=image2.png`, {
headers: { Authorization: `Bearer ${UPLOAD_SECRET}` },
});
expect(res.status).toBe(200);
const body = await res.json();
expect(body.url).toMatch(/^https:\/\/.+r2\.cloudflarestorage\.com/);
expect(body.key).toMatch(/^videos\/.+image2\.png$/);
});
});
describe('R2 upload', () => {
it('uploads image2.png successfully', async () => {
const presignRes = await fetch(`${WORKER_URL}/presign?filename=image2.png`, {
headers: { Authorization: `Bearer ${UPLOAD_SECRET}` },
});
const { url } = await presignRes.json();
const uploadRes = await fetch(url, {
method: 'PUT',
headers: { 'Content-Type': 'image/png' },
body: IMAGE,
});
expect(uploadRes.status).toBe(200);
});
});