From 88fb11e4efee03aff92c17892d17ca412a6c5682 Mon Sep 17 00:00:00 2001 From: fengmk2 Date: Sun, 22 Dec 2024 11:17:47 +0800 Subject: [PATCH] fix: allow sub class to override event methods --- .github/workflows/nodejs.yml | 2 +- package.json | 1 + src/index.ts | 2 +- test/index.test.ts | 16 ++++++++++++++++ 4 files changed, 19 insertions(+), 2 deletions(-) diff --git a/.github/workflows/nodejs.yml b/.github/workflows/nodejs.yml index 22c1cce..9ed9cf2 100644 --- a/.github/workflows/nodejs.yml +++ b/.github/workflows/nodejs.yml @@ -11,6 +11,6 @@ jobs: name: Node.js uses: node-modules/github-actions/.github/workflows/node-test.yml@master with: - version: '18.19.0, 18, 20, 22' + version: '18.19.0, 18, 20, 22, 23' secrets: CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} diff --git a/package.json b/package.json index 04cf686..ddb37ef 100644 --- a/package.json +++ b/package.json @@ -41,6 +41,7 @@ "lint": "eslint --cache src test --ext .ts", "pretest": "npm run lint -- --fix && npm run prepublishOnly", "test": "egg-bin test -p --timeout 5000", + "test-local": "egg-bin test --timeout 5000", "preci": "npm run lint && npm run prepublishOnly && attw --pack", "ci": "egg-bin cov -p", "prepublishOnly": "tshy && tshy-after" diff --git a/src/index.ts b/src/index.ts index db2429f..2761c45 100644 --- a/src/index.ts +++ b/src/index.ts @@ -45,7 +45,7 @@ export abstract class Base extends ReadyEventEmitter { } this.options = options ?? {}; this.#localStorage = this.options.localStorage ?? getAsyncLocalStorage(); - this.on('error', err => { + super.on('error', err => { this._defaultErrorHandler(err); }); } diff --git a/test/index.test.ts b/test/index.test.ts index ea37572..93704ce 100644 --- a/test/index.test.ts +++ b/test/index.test.ts @@ -6,7 +6,23 @@ import { Base, BaseOptions } from '../src/index.js'; describe('test/index.test.ts', () => { class SomeServiceClient extends Base {} + class SomeServiceClient2 extends Base { + protected _lists: any[] = []; + + on(...args: any[]) { + this._lists.push(args); + super.on(args[0], args[1]); + return this; + } + } + describe('default error handler', () => { + it('should allow subclass to override on methods', () => { + const c = new SomeServiceClient2(); + c.on('error', () => {}); + assert.equal(c.listeners('error').length, 2); + }); + it('should auto add the default error handler and show error message', () => { const c = new SomeServiceClient(); assert.equal(c.listeners('error').length, 1);