fix: correct removeAllListeners in case no event is passed (#2088)

Co-authored-by: Valentin Marchaud <contact@vmarchaud.fr>
This commit is contained in:
Gerhard Stöbich 2021-04-09 11:31:51 +02:00 committed by GitHub
parent 4a3fd1f4d8
commit a2fff0dd2e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 26 additions and 4 deletions

View File

@ -146,10 +146,14 @@ export abstract class AbstractAsyncHooksContextManager
const contextManager = this;
return function (this: never, event: string) {
const map = contextManager._getPatchMap(ee);
if (map?.[event] !== undefined) {
delete map[event];
if (map !== undefined) {
if (arguments.length === 0) {
contextManager._createPatchMap(ee);
} else if (map[event] !== undefined) {
delete map[event];
}
}
return original.call(this, event);
return original.apply(this, arguments);
};
}
@ -184,7 +188,7 @@ export abstract class AbstractAsyncHooksContextManager
}
private _createPatchMap(ee: EventEmitter): PatchMap {
const map = {};
const map = Object.create(null);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(ee as any)[this._kOtListeners] = map;
return map;

View File

@ -415,6 +415,24 @@ for (const contextManagerClass of [
patchedEE.emit('test');
});
it('should return current context and removeAllListeners (when enabled)', done => {
const ee = new EventEmitter();
const context = ROOT_CONTEXT.setValue(key1, 1);
const patchedEE = contextManager.bind(ee, context);
const handler = () => {
assert.deepStrictEqual(contextManager.active(), context);
patchedEE.removeAllListeners();
assert.strictEqual(patchedEE.listeners('test').length, 0);
assert.strictEqual(patchedEE.listeners('test1').length, 0);
return done();
};
patchedEE.on('test', handler);
patchedEE.on('test1', handler);
assert.strictEqual(patchedEE.listeners('test').length, 1);
assert.strictEqual(patchedEE.listeners('test1').length, 1);
patchedEE.emit('test');
});
/**
* Even if asynchooks is disabled, the context propagation will
* still works but it might be lost after any async op.