Skip to content

Commit 49a5cda

Browse files
committed
fix: sometimes tests failed
Sometimes the tests failed because of leaking async ops, that were caused by a `setTimeout`. Added a awaitable function that resolves after the timeout and call of the function
1 parent 26c4e42 commit 49a5cda

File tree

1 file changed

+30
-11
lines changed

1 file changed

+30
-11
lines changed

EventEmitter.test.ts

Lines changed: 30 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,27 @@ import {
66
fail,
77
} from "https://deno.land/std@0.127.0/testing/asserts.ts";
88

9+
const waitForTimeout = (
10+
fn: (args?: unknown[]) => void | Promise<void>,
11+
timeout: number,
12+
// deno-lint-ignore no-explicit-any
13+
...args: any[]
14+
): Promise<void> => {
15+
return new Promise((resolve) => {
16+
const timeoutId = setTimeout(
17+
async (args) => {
18+
await fn(args);
19+
20+
clearTimeout(timeoutId);
21+
22+
resolve();
23+
},
24+
timeout,
25+
...args,
26+
);
27+
});
28+
};
29+
930
Deno.test("EventEmitter", async (ctx) => {
1031
type ReservedEvents = {
1132
reserved: string;
@@ -21,12 +42,14 @@ Deno.test("EventEmitter", async (ctx) => {
2142
constructor() {
2243
super();
2344

24-
const timeout = setTimeout(() => {
45+
this.run();
46+
}
47+
48+
protected async run() {
49+
await waitForTimeout(() => {
2550
this.emitReserved("reserved", "reserved");
2651

2752
this.emitReserved("reserved2", ["reserved2"]);
28-
29-
clearTimeout(timeout);
3053
}, 10);
3154
}
3255
}
@@ -193,36 +216,32 @@ Deno.test("EventEmitter base functions", async (ctx) => {
193216
});
194217

195218
await ctx.step("pull", async (ctx) => {
196-
await ctx.step("without timeout", () => {
219+
await ctx.step("without timeout", async () => {
197220
const target = new EventEmitter<Events>();
198221

199222
const promise = target.pull("foo");
200223

201-
const timeout = setTimeout(async () => {
224+
await waitForTimeout(async () => {
202225
target.emit("foo", "bar");
203226

204227
const detail = await promise;
205228

206229
assertStrictEquals(detail, "bar");
207-
208-
clearTimeout(timeout);
209230
}, 10);
210231
});
211232

212233
await ctx.step("with timeout", async (ctx) => {
213-
await ctx.step("should resolve", () => {
234+
await ctx.step("should resolve", async () => {
214235
const target = new EventEmitter<Events>();
215236

216237
const promise = target.pull("foo", 20);
217238

218-
const timeout = setTimeout(async () => {
239+
await waitForTimeout(async () => {
219240
target.emit("foo", "bar");
220241

221242
const detail = await promise;
222243

223244
assertStrictEquals(detail, "bar");
224-
225-
clearTimeout(timeout);
226245
}, 10);
227246
});
228247

0 commit comments

Comments
 (0)