Last active
July 8, 2023 14:44
-
-
Save esdee/06dc078cd506f2e0ad9469cf37030316 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
------------------------------------------------------------------------------------ | |
/src/routes/api/hello.ts | |
import { type RequestEvent, type RequestHandler } from '@builder.io/qwik-city'; | |
export const onGet: RequestHandler = async ({ json }) => { | |
json(200, { hello: 'world GET' }); | |
}; | |
export const onPost: RequestHandler = async (requestEvent: RequestEvent) => { | |
const body = await requestEvent.parseBody(); | |
const authKey = 'authentication' as const; | |
const authToken = requestEvent.request.headers.get(authKey); | |
console.log(authKey, authToken); | |
if (authToken === 'test-auth-key') { | |
requestEvent.json(200, { hello: 'world POST', body }); | |
} else { | |
requestEvent.json(401, { message: 'Auth failure' }); | |
} | |
}; | |
--------------------------------------------------------------------------------- | |
/test/api/hello.test.ts | |
import { onGet, onPost } from '@api/hello/index'; | |
import { type RequestEvent } from '@builder.io/qwik-city'; | |
import { afterEach, describe, expect, test, vi } from 'vitest'; | |
describe('hello', () => { | |
afterEach(() => { | |
vi.restoreAllMocks(); | |
}); | |
test('authenticated POST', async () => { | |
let expectedJson; | |
let expectedStatus; | |
const mockRequestEvent = { | |
json: (status: number, body: unknown) => { | |
expectedJson = body; | |
expectedStatus = status; | |
}, | |
parseBody: async () => { | |
return { hello: 'world' }; | |
}, | |
request: { | |
headers: { | |
get: (k: string) => { | |
if (k === 'authentication') { | |
return 'test-auth-key'; | |
} | |
return null; | |
}, | |
}, | |
}, | |
} as unknown as RequestEvent; | |
await onPost(mockRequestEvent); | |
expect(expectedJson).toEqual({ | |
hello: 'world POST', | |
body: { hello: 'world' }, | |
}); | |
expect(expectedStatus).toEqual(200); | |
}); | |
test('GET', async () => { | |
let expectedJson; | |
let expectedStatus; | |
const mockRequestEvent = { | |
json: (status: number, body: unknown) => { | |
expectedJson = body; | |
expectedStatus = status; | |
}, | |
} as unknown as RequestEvent; | |
await onGet(mockRequestEvent); | |
expect(expectedJson).toEqual({ | |
hello: 'world GET', | |
}); | |
expect(expectedStatus).toEqual(200); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment