Skip to content

Commit

Permalink
Fix total phase when aborting after response was emitted
Browse files Browse the repository at this point in the history
  • Loading branch information
szmarczak committed Feb 3, 2020
1 parent cdac080 commit d27f8da
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 5 deletions.
6 changes: 5 additions & 1 deletion source/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,11 @@ const timer = (request: ClientRequestWithTimings): Timings => {

request.prependOnceListener('abort', (): void => {
timings.abort = Date.now();
timings.phases.total = Date.now() - timings.start;

// Let the `end` response event be responsible for setting the total phase
if (!timings.response) {
timings.phases.total = Date.now() - timings.start;
}
});

const onSocket = (socket: Socket): void => {
Expand Down
28 changes: 24 additions & 4 deletions tests/test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -183,16 +183,36 @@ test('sets `total` on response error', async t => {
t.is(timings.phases.total, timings.error! - timings.start);
});

test('sets `total` on abort', async t => {
test.cb('sets `total` on abort', t => {
const request = http.get(server.url!);
request.abort();

const timings = timer(request);

await pEvent(request, 'abort');
process.nextTick(() => {
t.is(typeof timings.abort, 'number');
t.is(timings.phases.total, timings.abort! - timings.start);
t.falsy((request as any).res);

t.is(typeof timings.abort, 'number');
t.is(timings.phases.total, timings.abort! - timings.start);
t.end();
});
});

test.cb('sets `total` on abort - after `response` event', t => {
const request = http.get(server.url!);
const timings = timer(request);

request.once('response', response => {
request.abort();

response.once('end', () => {
t.is(typeof timings.abort, 'number');
t.is(timings.phases.total, timings.end! - timings.start);
t.truthy((request as any).res);

t.end();
});
});
});

test('doesn\'t throw when someone used `.prependOnceListener()`', t => {
Expand Down

0 comments on commit d27f8da

Please sign in to comment.