Skip to content

Commit

Permalink
Add test for reportRequestMetric
Browse files Browse the repository at this point in the history
  • Loading branch information
pyropy committed Dec 12, 2024
1 parent 8fc77ed commit c43b0d5
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 7 deletions.
43 changes: 39 additions & 4 deletions test/influx.test.js
Original file line number Diff line number Diff line change
@@ -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()
Expand Down Expand Up @@ -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)

Expand Down
6 changes: 3 additions & 3 deletions test/worker.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});
});

0 comments on commit c43b0d5

Please sign in to comment.