diff --git a/test/influx.test.js b/test/influx.test.js index 50e75b7..a11b94a 100644 --- a/test/influx.test.js +++ b/test/influx.test.js @@ -1,5 +1,42 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' -import { createMetricsFromRequest, writeMetrics } from '../lib/influx.js' +import { createMetricsFromRequest, writeMetrics, reportRequestMetric } from '../lib/influx.js' + +describe('reportRequestMetric', () => { + const date = new Date() + + beforeEach(() => { + vi.useFakeTimers() + vi.setSystemTime(date) + }) + + afterEach(() => { + vi.useRealTimers() + }) + + it('reports request metrics to InfluxDB over HTTP', async () => { + const env = withTestEnvitronment() + const request = { + url: 'https://example.com/path', + method: 'GET', + headers: new Map([['api-key', 'test-key']]), + } + global.fetch = vi.fn().mockResolvedValue(new Response(null, { status: 204 })); + + await reportRequestMetric(request, env); + + expect(global.fetch).toHaveBeenCalledWith( + 'https://influx.example.com/api/v2/write?&bucket=test_db&precision=ms', + expect.objectContaining({ + method: 'POST', + headers: expect.objectContaining({ + Authorization: 'Token test_token', + 'Content-Type': 'application/octet-stream', + }), + body: `test_metric api_key="test-key" ${date.getTime()}`, + }), + ) + }); +}); describe('createMetricsFromRequest', () => { const date = new Date() @@ -65,9 +102,7 @@ describe('writeMetrics', () => { it('send request metrics to InfluxDB over HTTP', async () => { const env = withTestEnvitronment() const lineProtocolData = 'test_metric api_key="test-key"' - global.fetch = vi - .fn() - .mockResolvedValue(new Response(null, { status: 204 })) + global.fetch = vi.fn().mockResolvedValue(new Response(null, { status: 204 })) const response = await writeMetrics(lineProtocolData, env) diff --git a/test/worker.test.js b/test/worker.test.js index f38961f..8b4b7c1 100644 --- a/test/worker.test.js +++ b/test/worker.test.js @@ -11,12 +11,12 @@ describe('worker.fetch', () => { const ctx = { waitUntil: vi.fn() }; - global.fetch = vi.fn().mockResolvedValue(new Response(null, { status: 204 })); + global.fetch = vi.fn().mockResolvedValue(new Response(null, { status: 200 })); const reportRequestMetric = vi.fn() const response = await worker.fetch(request, env, ctx, { reportRequestMetric }); expect(global.fetch).toHaveBeenCalledWith(request); - expect(ctx.waitUntil).toHaveBeenCalledWith(reportRequestMetric(request, env)); expect(reportRequestMetric).toHaveBeenCalledWith(request, env); - expect(response.status).toBe(204); + expect(ctx.waitUntil).toHaveBeenCalledWith(reportRequestMetric(request, env)); + expect(response.status).toBe(200); }); });