Skip to content

Commit b76d53a

Browse files
committed
Add a test for the client, and fix the URL bugs it found
Previously we passed host instead of hostname (so it broke on non-default ports) and lost the query string entirely.
1 parent 59c5a29 commit b76d53a

File tree

2 files changed

+49
-6
lines changed

2 files changed

+49
-6
lines changed

src/client/client.ts

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -28,12 +28,7 @@ export async function sendRequest(
2828
): Promise<ResponseDefinition> {
2929
const url = new URL(requestDefn.url);
3030

31-
const request = (url.protocol === 'https:' ? https : http).request({
32-
protocol: url.protocol,
33-
host: url.host,
34-
port: url.port,
35-
path: url.pathname,
36-
31+
const request = (url.protocol === 'https' ? https : http).request(requestDefn.url, {
3732
method: requestDefn.method,
3833

3934
// Node supports sending raw headers via [key, value, key, value] array, but we need an

test/client/send-request.spec.ts

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
import { expect } from 'chai';
2+
import * as mockttp from 'mockttp';
3+
4+
import { sendRequest } from '../../src/client/client';
5+
6+
describe("The HTTP client API", () => {
7+
8+
const mockServer = mockttp.getLocal({ debug: true });
9+
10+
beforeEach(() => mockServer.start());
11+
afterEach(() => mockServer.stop());
12+
13+
it("should send requests", async () => {
14+
await mockServer.forAnyRequest().thenCallback(async (request) => {
15+
expect(request.url).to.equal(`http://localhost:${mockServer.port}/path?qwe=asd`);
16+
expect(request.method).to.equal('POST');
17+
expect(
18+
request.rawHeaders.find(([key]) => key === 'CUSTOM-header')
19+
).to.deep.equal(['CUSTOM-header', 'CUSTOM-value']);
20+
expect(await request.body.getText()).to.equal('Request body')
21+
22+
return {
23+
statusCode: 200,
24+
statusMessage: 'Custom status message',
25+
headers: { 'custom-HEADER': 'custom-VALUE' },
26+
rawBody: Buffer.from('Mock response body')
27+
};
28+
});
29+
30+
const response = await sendRequest({
31+
url: mockServer.urlFor('/path?qwe=asd'),
32+
method: 'POST',
33+
headers: [
34+
['host', `localhost:${mockServer.port}`],
35+
['content-length', '12'],
36+
['CUSTOM-header', 'CUSTOM-value']
37+
],
38+
rawBody: Buffer.from('Request body')
39+
}, {});
40+
41+
expect(response.statusCode).to.equal(200);
42+
expect(response.statusMessage).to.equal('Custom status message');
43+
expect(response.headers).to.deep.equal([
44+
['custom-HEADER', 'custom-VALUE']
45+
]);
46+
expect(response.rawBody!.toString()).to.equal('Mock response body');
47+
})
48+
});

0 commit comments

Comments
 (0)