Skip to content

Commit

Permalink
test: improve test server teardown
Browse files Browse the repository at this point in the history
  • Loading branch information
smeijer committed Sep 15, 2021
1 parent 39d872b commit 907889d
Showing 1 changed file with 14 additions and 11 deletions.
25 changes: 14 additions & 11 deletions src/__utils__/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,11 @@ async function request(
}

export async function next(getServerSideProps: GetServerSideProps) {
let lastRequest = Date.now();

const server = http.createServer((req, res) => {
lastRequest = Date.now();

getServerSideProps({
req,
res,
Expand All @@ -72,18 +76,17 @@ export async function next(getServerSideProps: GetServerSideProps) {
});
});

const url = await listen(server);
const timeout = null;
const interval = setInterval(() => {
if (Date.now() - lastRequest < 50) return;
clearInterval(interval);
server.close();
}, 3);

return async (path = '/', options?: RequestOptions) => {
clearTimeout(timeout);
const result = await request(`${url}${path}`, options);
const url = await listen(server);

// give it 25 ms for another request to come in, close after that
setTimeout(() => {
server.close();
}, 25);
const fetch = async (path = '/', options?: RequestOptions) =>
request(`${url}${path}`, options);

return result;
};
fetch.url = url;
return fetch;
}

0 comments on commit 907889d

Please sign in to comment.