Skip to content

Commit

Permalink
test: update server tests
Browse files Browse the repository at this point in the history
  • Loading branch information
MichaelKreil committed Mar 7, 2024
1 parent 91abdec commit a9ec83a
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
2 changes: 2 additions & 0 deletions src/lib/__mocks__/global_fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ export function mockFetchResponse(data: unknown): void {
// @ts-expect-error too lazy
global.fetch = jest.fn(async () => Promise.resolve({
arrayBuffer: async () => Promise.resolve(getAsBuffer()),
// eslint-disable-next-line @typescript-eslint/naming-convention
headers: new Headers({ 'content-type': 'text/plain' }),
json: async () => Promise.resolve(getAsJSON()),
status: 200,
}));
Expand Down
23 changes: 22 additions & 1 deletion src/server/server.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,15 @@ describe('Server', () => {
let getFunction: (req: IncomingMessage, res: ServerResponse) => void;

async function fakeRequest(path: string): Promise<{
header: jest.Mock<(key: string, value: string) => void>;
status: jest.Mock<(status: number) => void>;
end: jest.Mock<(data: Buffer | string) => void>;
}> {
return new Promise(resolve => {
const response = {
status: jest.fn().mockReturnThis(), end: jest.fn(() => {
status: jest.fn().mockReturnThis(),
header: jest.fn().mockReturnThis(),
end: jest.fn(() => {
resolve(response);
}),
};
Expand Down Expand Up @@ -63,22 +66,40 @@ describe('Server', () => {
it('should serve files from the file system', async () => {
const res = await fakeRequest('/existingFile.txt');

expect(res.header).toHaveBeenCalledTimes(1);
expect(res.header).toHaveBeenCalledWith('content-type', 'text/plain');

expect(res.status).toHaveBeenCalledTimes(1);
expect(res.status).toHaveBeenCalledWith(200);

expect(res.end).toHaveBeenCalledTimes(1);
expect(res.end).toHaveBeenCalledWith(Buffer.from('file content'));
});

it('should return 404 for non-existing files', async () => {
const res = await fakeRequest('/nonExistingFile.txt');

expect(res.header).toHaveBeenCalledTimes(0);

expect(res.status).toHaveBeenCalledTimes(1);
expect(res.status).toHaveBeenCalledWith(404);

expect(res.end).toHaveBeenCalledTimes(1);
expect(res.end).toHaveBeenCalledWith(expect.stringContaining('not found'));
});

it('should proxy requests based on configuration', async () => {
const res = await fakeRequest('/api/data');

expect(fetch).toHaveBeenCalledWith('http://example.com/api/data');

expect(res.header).toHaveBeenCalledTimes(1);
expect(res.header).toHaveBeenCalledWith('content-type', 'text/plain');

expect(res.status).toHaveBeenCalledTimes(1);
expect(res.status).toHaveBeenCalledWith(200);

expect(res.end).toHaveBeenCalledTimes(1);
expect(res.end).toHaveBeenCalledWith(Buffer.from('response'));
});
});

0 comments on commit a9ec83a

Please sign in to comment.