This is an automated email from the ASF dual-hosted git repository.

RongtongJin pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/rocketmq-clients.git


The following commit(s) were added to refs/heads/master by this push:
     new ae50c8c9 fix(nodejs): make unit test failures fail the CI gate (#1500)
ae50c8c9 is described below

commit ae50c8c917d45f67bda468e36886888376698a8d
Author: Quan <[email protected]>
AuthorDate: Wed Nov 18 17:34:33 2026 +0800

    fix(nodejs): make unit test failures fail the CI gate (#1500)
    
    - Run all tests under Mocha and forbid node:test imports
    - Isolate broker integration tests and enforce unit coverage in CI
    - Add shared test doubles and stub builder startup
---
 .github/workflows/nodejs_build.yml                 |  10 +-
 nodejs/.eslintrc                                   |   5 +-
 nodejs/package-lock.json                           | 148 ++++++++++++++++++
 nodejs/package.json                                |   7 +-
 nodejs/test/client/BaseClient.test.ts              |   1 -
 nodejs/test/client/TelemetrySession.test.ts        |   1 -
 nodejs/test/consumer/ConsumeResult.test.ts         |   1 -
 nodejs/test/consumer/FifoConsumeService.test.ts    |   1 -
 .../test/consumer/LiteFifoConsumeService.test.ts   |   1 -
 .../test/consumer/LitePushConsumerBuilder.test.ts  |  36 +++--
 nodejs/test/consumer/LiteSimpleConsumer.test.ts    |   1 -
 nodejs/test/consumer/OffsetOption.test.ts          |   1 -
 nodejs/test/consumer/ProcessQueue.test.ts          |   1 -
 .../test/consumer/PushConsumerShutdownRace.test.ts |   3 +-
 .../LiteSubscriptionQuotaExceededException.test.ts |   1 -
 nodejs/test/fixes.test.ts                          |   1 -
 nodejs/test/helper.ts                              |   1 +
 nodejs/test/hook.test.ts                           |   1 -
 .../LiteSimpleConsumer.test.ts}                    |   5 +-
 .../{producer => integration}/Producer.test.ts     |   4 +-
 .../SimpleConsumer.test.ts                         |   4 +-
 nodejs/test/message/LiteMessage.test.ts            |   1 -
 nodejs/test/message/PriorityMessage.test.ts        |   1 -
 nodejs/test/message/PublishingLiteMessage.test.ts  |   1 -
 nodejs/test/metrics.test.ts                        |   1 -
 .../test/producer/PublishingLoadBalancer.test.ts   |   1 -
 nodejs/test/route/Endpoints.test.ts                |   1 -
 nodejs/test/route/IpNameResolver.test.ts           |   1 -
 nodejs/test/support/fakes.ts                       | 108 +++++++++++++
 nodejs/test/support/protobuf.ts                    | 128 ++++++++++++++++
 nodejs/test/support/support.test.ts                | 167 +++++++++++++++++++++
 nodejs/test/util/Semaphore.test.ts                 |   1 -
 32 files changed, 601 insertions(+), 44 deletions(-)

diff --git a/.github/workflows/nodejs_build.yml 
b/.github/workflows/nodejs_build.yml
index f8b37b71..3173ca9d 100644
--- a/.github/workflows/nodejs_build.yml
+++ b/.github/workflows/nodejs_build.yml
@@ -23,4 +23,12 @@ jobs:
 
       - name: Build
         working-directory: ./nodejs
-        run: npm i && npm run init && npm run build && npm pack
+        run: npm ci && npm run build && npm pack
+
+      - name: Lint
+        working-directory: ./nodejs
+        run: npm run lint
+
+      - name: Unit tests and coverage
+        working-directory: ./nodejs
+        run: npm run cov
diff --git a/nodejs/.eslintrc b/nodejs/.eslintrc
index 9bcdb468..3dbf770f 100644
--- a/nodejs/.eslintrc
+++ b/nodejs/.eslintrc
@@ -2,5 +2,8 @@
   "extends": [
     "eslint-config-egg/typescript",
     "eslint-config-egg/lib/rules/enforce-node-prefix"
-  ]
+  ],
+  "rules": {
+    "no-restricted-imports": ["error", "node:test"]
+  }
 }
diff --git a/nodejs/package-lock.json b/nodejs/package-lock.json
index 9bc8ea60..6086cdf7 100644
--- a/nodejs/package-lock.json
+++ b/nodejs/package-lock.json
@@ -25,11 +25,13 @@
         "@types/google-protobuf": "^3.15.6",
         "@types/mocha": "^10.0.1",
         "@types/node": "^20.5.7",
+        "@types/sinon": "^17.0.4",
         "egg-bin": "^6.4.2",
         "eslint": "^8.48.0",
         "eslint-config-egg": "^12.2.1",
         "grpc_tools_node_protoc_ts": "^5.3.3",
         "grpc-tools": "^1.12.4",
+        "sinon": "^17.0.1",
         "typescript": "^5.2.2"
       },
       "engines": {
@@ -1561,6 +1563,55 @@
       "integrity": 
"sha512-MTBk/3jGLNB2tVxv6uLlFh1iu64iYOQ2PbdOSK3NW8JZsmlaOh2q6sdtKowBhfw8QFLmYNzTW4/oK4uATIi6ZA==",
       "dev": true
     },
+    "node_modules/@sinonjs/commons": {
+      "version": "3.0.1",
+      "resolved": 
"https://registry.npmjs.org/@sinonjs/commons/-/commons-3.0.1.tgz";,
+      "integrity": 
"sha512-K3mCHKQ9sVh8o1C9cxkwxaOmXoAMlDxC1mYyHrjqOWEcBjYr76t96zL2zlj5dUGZ3HSw240X1qgH3Mjf1yJWpQ==",
+      "dev": true,
+      "license": "BSD-3-Clause",
+      "dependencies": {
+        "type-detect": "4.0.8"
+      }
+    },
+    "node_modules/@sinonjs/fake-timers": {
+      "version": "11.3.1",
+      "resolved": 
"https://registry.npmjs.org/@sinonjs/fake-timers/-/fake-timers-11.3.1.tgz";,
+      "integrity": 
"sha512-EVJO7nW5M/F5Tur0Rf2z/QoMo+1Ia963RiMtapiQrEWvY0iBUvADo8Beegwjpnle5BHkyHuoxSTW3jF43H1XRA==",
+      "dev": true,
+      "license": "BSD-3-Clause",
+      "dependencies": {
+        "@sinonjs/commons": "^3.0.1"
+      }
+    },
+    "node_modules/@sinonjs/samsam": {
+      "version": "8.0.3",
+      "resolved": 
"https://registry.npmjs.org/@sinonjs/samsam/-/samsam-8.0.3.tgz";,
+      "integrity": 
"sha512-hw6HbX+GyVZzmaYNh82Ecj1vdGZrqVIn/keDTg63IgAwiQPO+xCz99uG6Woqgb4tM0mUiFENKZ4cqd7IX94AXQ==",
+      "dev": true,
+      "license": "BSD-3-Clause",
+      "dependencies": {
+        "@sinonjs/commons": "^3.0.1",
+        "type-detect": "^4.1.0"
+      }
+    },
+    "node_modules/@sinonjs/samsam/node_modules/type-detect": {
+      "version": "4.1.0",
+      "resolved": 
"https://registry.npmjs.org/type-detect/-/type-detect-4.1.0.tgz";,
+      "integrity": 
"sha512-Acylog8/luQ8L7il+geoSxhEkazvkslg7PSNKOX59mbB9cOveP5aq9h74Y7YU8yDpJwetzQQrfIwtf4Wp4LKcw==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">=4"
+      }
+    },
+    "node_modules/@sinonjs/text-encoding": {
+      "version": "0.7.3",
+      "resolved": 
"https://registry.npmjs.org/@sinonjs/text-encoding/-/text-encoding-0.7.3.tgz";,
+      "integrity": 
"sha512-DE427ROAphMQzU4ENbliGYrBSYPXF+TtLg9S8vzeA+OF4ZKzoDdzfL8sxuMUGS/lgRhM6j1URSk9ghf7Xo1tyA==",
+      "deprecated": "Deprecated: no longer maintained and no longer used by 
Sinon packages. See\n  https://github.com/sinonjs/nise/issues/243 for 
replacement details.",
+      "dev": true,
+      "license": "(Unlicense OR Apache-2.0)"
+    },
     "node_modules/@tsconfig/node10": {
       "version": "1.0.12",
       "resolved": 
"https://registry.npmjs.org/@tsconfig/node10/-/node10-1.0.12.tgz";,
@@ -1656,6 +1707,23 @@
       "integrity": 
"sha512-FmgJfu+MOcQ370SD0ev7EI8TlCAfKYU+B4m5T3yXc1CiRN94g/SZPtsCkk506aUDtlMnFZvasDwHHUcZUEaYuA==",
       "dev": true
     },
+    "node_modules/@types/sinon": {
+      "version": "17.0.4",
+      "resolved": "https://registry.npmjs.org/@types/sinon/-/sinon-17.0.4.tgz";,
+      "integrity": 
"sha512-RHnIrhfPO3+tJT0s7cFaXGZvsL4bbR3/k7z3P312qMS4JaS2Tk+KiwiLx1S0rQ56ERj00u1/BtdyVd0FY+Pdew==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "@types/sinonjs__fake-timers": "*"
+      }
+    },
+    "node_modules/@types/sinonjs__fake-timers": {
+      "version": "15.0.1",
+      "resolved": 
"https://registry.npmjs.org/@types/sinonjs__fake-timers/-/sinonjs__fake-timers-15.0.1.tgz";,
+      "integrity": 
"sha512-Ko2tjWJq8oozHzHV+reuvS5KYIRAokHnGbDwGh/J64LntgpbuylF74ipEL24HCyRjf9FOlBiBHWBR1RlVKsI1w==",
+      "dev": true,
+      "license": "MIT"
+    },
     "node_modules/@types/yargs": {
       "version": "17.0.35",
       "resolved": 
"https://registry.npmjs.org/@types/yargs/-/yargs-17.0.35.tgz";,
@@ -5870,6 +5938,13 @@
         "node": ">=4.0"
       }
     },
+    "node_modules/just-extend": {
+      "version": "6.2.0",
+      "resolved": 
"https://registry.npmjs.org/just-extend/-/just-extend-6.2.0.tgz";,
+      "integrity": 
"sha512-cYofQu2Xpom82S6qD778jBDpwvvy39s1l/hrYij2u9AMdQcGRpaBu6kY4mVhuno5kJVi1DAz4aiphA2WI1/OAw==",
+      "dev": true,
+      "license": "MIT"
+    },
     "node_modules/keyv": {
       "version": "4.5.4",
       "resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz";,
@@ -6580,6 +6655,20 @@
       "integrity": 
"sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw==",
       "dev": true
     },
+    "node_modules/nise": {
+      "version": "5.1.9",
+      "resolved": "https://registry.npmjs.org/nise/-/nise-5.1.9.tgz";,
+      "integrity": 
"sha512-qOnoujW4SV6e40dYxJOb3uvuoPHtmLzIk4TFo+j0jPJoC+5Z9xja5qH5JZobEPsa8+YYphMrOSwnrshEhG2qww==",
+      "dev": true,
+      "license": "BSD-3-Clause",
+      "dependencies": {
+        "@sinonjs/commons": "^3.0.0",
+        "@sinonjs/fake-timers": "^11.2.2",
+        "@sinonjs/text-encoding": "^0.7.2",
+        "just-extend": "^6.2.0",
+        "path-to-regexp": "^6.2.1"
+      }
+    },
     "node_modules/node-exports-info": {
       "version": "1.6.0",
       "resolved": 
"https://registry.npmjs.org/node-exports-info/-/node-exports-info-1.6.0.tgz";,
@@ -7047,6 +7136,13 @@
       "integrity": 
"sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==",
       "dev": true
     },
+    "node_modules/path-to-regexp": {
+      "version": "6.3.0",
+      "resolved": 
"https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-6.3.0.tgz";,
+      "integrity": 
"sha512-Yhpw4T9C6hPpgPeA28us07OJeqZ5EzQTkbfwuhsUg0c237RomFoETJgmp2sa3F/41gfLE6G5cqcYwznmeEeOlQ==",
+      "dev": true,
+      "license": "MIT"
+    },
     "node_modules/path-type": {
       "version": "4.0.0",
       "resolved": "https://registry.npmjs.org/path-type/-/path-type-4.0.0.tgz";,
@@ -7766,6 +7862,48 @@
         "url": "https://github.com/sponsors/isaacs";
       }
     },
+    "node_modules/sinon": {
+      "version": "17.0.1",
+      "resolved": "https://registry.npmjs.org/sinon/-/sinon-17.0.1.tgz";,
+      "integrity": 
"sha512-wmwE19Lie0MLT+ZYNpDymasPHUKTaZHUH/pKEubRXIzySv9Atnlw+BUMGCzWgV7b7wO+Hw6f1TEOr0IUnmU8/g==",
+      "dev": true,
+      "license": "BSD-3-Clause",
+      "dependencies": {
+        "@sinonjs/commons": "^3.0.0",
+        "@sinonjs/fake-timers": "^11.2.2",
+        "@sinonjs/samsam": "^8.0.0",
+        "diff": "^5.1.0",
+        "nise": "^5.1.5",
+        "supports-color": "^7.2.0"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/sinon";
+      }
+    },
+    "node_modules/sinon/node_modules/has-flag": {
+      "version": "4.0.0",
+      "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz";,
+      "integrity": 
"sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">=8"
+      }
+    },
+    "node_modules/sinon/node_modules/supports-color": {
+      "version": "7.2.0",
+      "resolved": 
"https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz";,
+      "integrity": 
"sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "has-flag": "^4.0.0"
+      },
+      "engines": {
+        "node": ">=8"
+      }
+    },
     "node_modules/siphash24": {
       "version": "1.3.1",
       "resolved": "https://registry.npmjs.org/siphash24/-/siphash24-1.3.1.tgz";,
@@ -8336,6 +8474,16 @@
         "node": ">= 0.8.0"
       }
     },
+    "node_modules/type-detect": {
+      "version": "4.0.8",
+      "resolved": 
"https://registry.npmjs.org/type-detect/-/type-detect-4.0.8.tgz";,
+      "integrity": 
"sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">=4"
+      }
+    },
     "node_modules/type-fest": {
       "version": "3.13.1",
       "resolved": 
"https://registry.npmjs.org/type-fest/-/type-fest-3.13.1.tgz";,
diff --git a/nodejs/package.json b/nodejs/package.json
index d985fd17..3dc51617 100644
--- a/nodejs/package.json
+++ b/nodejs/package.json
@@ -11,8 +11,9 @@
   ],
   "scripts": {
     "init": "npm run build:grpc",
-    "test": "egg-bin test",
-    "cov": "egg-bin cov",
+    "test": "egg-bin test \"test/**/*.test.ts\" \"!test/integration/**\"",
+    "test:integration": "egg-bin test \"test/integration/**/*.test.ts\"",
+    "cov": "egg-bin cov \"test/**/*.test.ts\" \"!test/integration/**\"",
     "lint": "eslint src test",
     "build:grpc": "scripts/build-grpc.sh",
     "clean": "rm -rf dist *.d.ts",
@@ -40,11 +41,13 @@
     "@types/google-protobuf": "^3.15.6",
     "@types/mocha": "^10.0.1",
     "@types/node": "^20.5.7",
+    "@types/sinon": "^17.0.4",
     "egg-bin": "^6.4.2",
     "eslint": "^8.48.0",
     "eslint-config-egg": "^12.2.1",
     "grpc_tools_node_protoc_ts": "^5.3.3",
     "grpc-tools": "^1.12.4",
+    "sinon": "^17.0.1",
     "typescript": "^5.2.2"
   },
   "dependencies": {
diff --git a/nodejs/test/client/BaseClient.test.ts 
b/nodejs/test/client/BaseClient.test.ts
index 544175a2..9e663449 100644
--- a/nodejs/test/client/BaseClient.test.ts
+++ b/nodejs/test/client/BaseClient.test.ts
@@ -29,7 +29,6 @@
  *    the route/settings/heartbeat timers.
  */
 
-import { describe, it } from 'node:test';
 import * as assert from 'node:assert';
 import { EventEmitter } from 'node:events';
 import { format } from 'node:util';
diff --git a/nodejs/test/client/TelemetrySession.test.ts 
b/nodejs/test/client/TelemetrySession.test.ts
index 76466b99..538cfcee 100644
--- a/nodejs/test/client/TelemetrySession.test.ts
+++ b/nodejs/test/client/TelemetrySession.test.ts
@@ -26,7 +26,6 @@
  * exponential backoff until release().
  */
 
-import { describe, it } from 'node:test';
 import * as assert from 'node:assert';
 import { EventEmitter } from 'node:events';
 import { TelemetrySession } from '../../src/client/TelemetrySession';
diff --git a/nodejs/test/consumer/ConsumeResult.test.ts 
b/nodejs/test/consumer/ConsumeResult.test.ts
index dab83d07..3ca661f5 100644
--- a/nodejs/test/consumer/ConsumeResult.test.ts
+++ b/nodejs/test/consumer/ConsumeResult.test.ts
@@ -15,7 +15,6 @@
  * limitations under the License.
  */
 
-import { describe, it } from 'node:test';
 import * as assert from 'node:assert';
 import { ConsumeResult, ConsumeResultSuspend } from 
'../../src/consumer/ConsumeResult';
 
diff --git a/nodejs/test/consumer/FifoConsumeService.test.ts 
b/nodejs/test/consumer/FifoConsumeService.test.ts
index 25b48655..40e3752e 100644
--- a/nodejs/test/consumer/FifoConsumeService.test.ts
+++ b/nodejs/test/consumer/FifoConsumeService.test.ts
@@ -19,7 +19,6 @@
  * Test for FIFO Consume Accelerator
  */
 
-import { describe, it } from 'node:test';
 import * as assert from 'node:assert';
 import { FifoConsumeService } from '../../src/consumer/FifoConsumeService';
 import { MessageListener } from '../../src/consumer/MessageListener';
diff --git a/nodejs/test/consumer/LiteFifoConsumeService.test.ts 
b/nodejs/test/consumer/LiteFifoConsumeService.test.ts
index 0697168e..3c039898 100644
--- a/nodejs/test/consumer/LiteFifoConsumeService.test.ts
+++ b/nodejs/test/consumer/LiteFifoConsumeService.test.ts
@@ -19,7 +19,6 @@
  * Test for Lite FIFO Consume Service
  */
 
-import { describe, it } from 'node:test';
 import * as assert from 'node:assert';
 import { LiteFifoConsumeService } from 
'../../src/consumer/LiteFifoConsumeService';
 import { MessageListener } from '../../src/consumer/MessageListener';
diff --git a/nodejs/test/consumer/LitePushConsumerBuilder.test.ts 
b/nodejs/test/consumer/LitePushConsumerBuilder.test.ts
index 9ee543b8..9a6dc98d 100644
--- a/nodejs/test/consumer/LitePushConsumerBuilder.test.ts
+++ b/nodejs/test/consumer/LitePushConsumerBuilder.test.ts
@@ -19,8 +19,9 @@
  * Test for LitePushConsumerBuilder
  */
 
-import { describe, it } from 'node:test';
 import * as assert from 'node:assert';
+import * as sinon from 'sinon';
+import { LitePushConsumerImpl } from '../../src/consumer/LitePushConsumerImpl';
 import { LitePushConsumerBuilder } from '../../src';
 import { BaseClientOptions } from '../../src/client';
 import { ConsumeResult } from '../../src';
@@ -186,11 +187,16 @@ describe('LitePushConsumerBuilder', () => {
       builder.setMessageListener(createMockMessageListener());
       builder.bindTopic('test-topic');
 
-      // Should reject because startup() requires a real RocketMQ server 
connection
-      await assert.rejects(
-        () => builder.build(),
-        /Failed to start|Connection|ECONNREFUSED|timeout|Timeout|Error/,
-      );
+      const startup = sinon.stub(LitePushConsumerImpl.prototype, 
'startup').resolves();
+      try {
+        const consumer = await builder.build();
+        assert.ok(consumer instanceof LitePushConsumerImpl);
+        consumer.getRpcClientManager().close();
+        sinon.assert.calledOnce(startup);
+        assert.strictEqual(startup.firstCall.thisValue, consumer);
+      } finally {
+        startup.restore();
+      }
     });
 
     it('should throw error when consumerGroup not set', async () => {
@@ -220,18 +226,24 @@ describe('LitePushConsumerBuilder', () => {
       await assert.rejects(() => builder.build(), /bindTopic has not been set 
yet/);
     });
 
-    it('should throw connection error when all params set but no server', 
async () => {
+    it('should propagate a startup error without connecting to a server', 
async () => {
       const builder = new LitePushConsumerBuilder();
       builder.setClientConfiguration(createMockClientConfig());
       builder.setConsumerGroup('test-group');
       builder.setMessageListener(createMockMessageListener());
       builder.bindTopic('test-topic');
 
-      // Should reject because startup() requires a real RocketMQ server 
connection
-      await assert.rejects(
-        () => builder.build(),
-        /Failed to start|Connection|ECONNREFUSED|timeout|Timeout|Error/,
-      );
+      const failure = new Error('startup failed');
+      const startup = sinon.stub(LitePushConsumerImpl.prototype, 
'startup').callsFake(async function(this: LitePushConsumerImpl) {
+        this.getRpcClientManager().close();
+        throw failure;
+      });
+      try {
+        await assert.rejects(() => builder.build(), error => error === 
failure);
+        sinon.assert.calledOnce(startup);
+      } finally {
+        startup.restore();
+      }
     });
   });
 });
diff --git a/nodejs/test/consumer/LiteSimpleConsumer.test.ts 
b/nodejs/test/consumer/LiteSimpleConsumer.test.ts
index 116bee05..bd612940 100644
--- a/nodejs/test/consumer/LiteSimpleConsumer.test.ts
+++ b/nodejs/test/consumer/LiteSimpleConsumer.test.ts
@@ -20,7 +20,6 @@
  * LiteSubscriptionManager. No broker required.
  */
 
-import { describe, it } from 'node:test';
 import * as assert from 'node:assert';
 import {
   Broker as BrokerPB,
diff --git a/nodejs/test/consumer/OffsetOption.test.ts 
b/nodejs/test/consumer/OffsetOption.test.ts
index a70a5e19..96cd8056 100644
--- a/nodejs/test/consumer/OffsetOption.test.ts
+++ b/nodejs/test/consumer/OffsetOption.test.ts
@@ -19,7 +19,6 @@
  * Test for OffsetOption
  */
 
-import { describe, it } from 'node:test';
 import * as assert from 'node:assert';
 import { OffsetOption, OffsetType } from '../../src/consumer/OffsetOption';
 
diff --git a/nodejs/test/consumer/ProcessQueue.test.ts 
b/nodejs/test/consumer/ProcessQueue.test.ts
index 22956385..268f7611 100644
--- a/nodejs/test/consumer/ProcessQueue.test.ts
+++ b/nodejs/test/consumer/ProcessQueue.test.ts
@@ -15,7 +15,6 @@
  * limitations under the License.
  */
 
-import { describe, it } from 'node:test';
 import * as assert from 'node:assert';
 import { ProcessQueue } from '../../src/consumer/ProcessQueue';
 import { FilterExpression } from '../../src/consumer/FilterExpression';
diff --git a/nodejs/test/consumer/PushConsumerShutdownRace.test.ts 
b/nodejs/test/consumer/PushConsumerShutdownRace.test.ts
index f53a2b7a..3e84a632 100644
--- a/nodejs/test/consumer/PushConsumerShutdownRace.test.ts
+++ b/nodejs/test/consumer/PushConsumerShutdownRace.test.ts
@@ -33,7 +33,6 @@
  * test asserts the late assignment can no longer resurrect the loop.
  */
 
-import { describe, it } from 'node:test';
 import * as assert from 'node:assert';
 import { EventEmitter } from 'node:events';
 import { PushConsumer } from '../../src/consumer/PushConsumer';
@@ -86,7 +85,7 @@ describe('PushConsumer shutdown vs in-flight assignment scan 
race', () => {
       namespace: '',
       consumerGroup: 'cg-race',
       subscriptions: new Map([[ 'topic-a', new FilterExpression('*') ]]),
-      messageListener: async () => 0 as never,
+      messageListener: { consume: async () => 0 as never },
     } as never);
 
     let receiveCalls = 0;
diff --git 
a/nodejs/test/exception/LiteSubscriptionQuotaExceededException.test.ts 
b/nodejs/test/exception/LiteSubscriptionQuotaExceededException.test.ts
index 24ee998a..fc601c21 100644
--- a/nodejs/test/exception/LiteSubscriptionQuotaExceededException.test.ts
+++ b/nodejs/test/exception/LiteSubscriptionQuotaExceededException.test.ts
@@ -19,7 +19,6 @@
  * Test for LiteSubscriptionQuotaExceededException
  */
 
-import { describe, it } from 'node:test';
 import * as assert from 'node:assert';
 import { LiteSubscriptionQuotaExceededException } from 
'../../src/exception/LiteSubscriptionQuotaExceededException';
 
diff --git a/nodejs/test/fixes.test.ts b/nodejs/test/fixes.test.ts
index 95a6b0fc..a43d4b90 100644
--- a/nodejs/test/fixes.test.ts
+++ b/nodejs/test/fixes.test.ts
@@ -24,7 +24,6 @@
  *    LITE_SUBSCRIPTION_QUOTA_EXCEEDED)
  */
 
-import { describe, it } from 'node:test';
 import * as assert from 'node:assert';
 import { Duration } from 'google-protobuf/google/protobuf/duration_pb';
 import {
diff --git a/nodejs/test/helper.ts b/nodejs/test/helper.ts
index 4cd23fa4..b74f2fad 100644
--- a/nodejs/test/helper.ts
+++ b/nodejs/test/helper.ts
@@ -17,6 +17,7 @@
 
 import { SessionCredentials } from '../src/client';
 
+export const describeIntegration = 
process.env.ROCKETMQ_NODEJS_CLIENT_ENDPOINTS?.trim() ? describe : describe.skip;
 export const endpoints = process.env.ROCKETMQ_NODEJS_CLIENT_ENDPOINTS ?? 
'localhost:8081';
 export const namespace = process.env.ROCKETMQ_NODEJS_CLIENT_NAMESPACE ?? '';
 export const topics = {
diff --git a/nodejs/test/hook.test.ts b/nodejs/test/hook.test.ts
index 30f7121c..6ceb165d 100644
--- a/nodejs/test/hook.test.ts
+++ b/nodejs/test/hook.test.ts
@@ -26,7 +26,6 @@
  *  - PushConsumer settlement hooks (K-4)
  */
 
-import { describe, it } from 'node:test';
 import * as assert from 'node:assert';
 import { Endpoints } from '../src/route';
 import { Producer } from '../src/producer';
diff --git a/nodejs/test/consumer/LiteSimpleConsumer.integration.test.ts 
b/nodejs/test/integration/LiteSimpleConsumer.test.ts
similarity index 97%
rename from nodejs/test/consumer/LiteSimpleConsumer.integration.test.ts
rename to nodejs/test/integration/LiteSimpleConsumer.test.ts
index 5f6d0bb3..157fc598 100644
--- a/nodejs/test/consumer/LiteSimpleConsumer.integration.test.ts
+++ b/nodejs/test/integration/LiteSimpleConsumer.test.ts
@@ -28,17 +28,16 @@
  * enableMultiDispatch=true so lite messages reach the LMQ queues.
  */
 
-import { describe, it, afterEach } from 'node:test';
 import * as assert from 'node:assert';
 import { Producer } from '../../src';
 import { LiteSimpleConsumerImpl } from 
'../../src/consumer/LiteSimpleConsumerImpl';
 import { OffsetOption } from '../../src/consumer/OffsetOption';
-import { endpoints, namespace } from '../helper';
+import { endpoints, namespace, describeIntegration } from '../helper';
 
 const BIND_TOPIC = process.env.ROCKETMQ_NODEJS_CLIENT_LITE_TOPIC ?? 
'lite-parent-topic';
 const CONSUMER_GROUP = process.env.ROCKETMQ_NODEJS_CLIENT_LITE_GROUP ?? 
'nodejs-lite-unittest-group';
 
-describe('test/consumer/LiteSimpleConsumer.integration.test.ts', () => {
+describeIntegration('test/integration/LiteSimpleConsumer.test.ts', () => {
   let producer: Producer | null = null;
   let consumer: LiteSimpleConsumerImpl | null = null;
 
diff --git a/nodejs/test/producer/Producer.test.ts 
b/nodejs/test/integration/Producer.test.ts
similarity index 98%
rename from nodejs/test/producer/Producer.test.ts
rename to nodejs/test/integration/Producer.test.ts
index 66deec77..97768930 100644
--- a/nodejs/test/producer/Producer.test.ts
+++ b/nodejs/test/integration/Producer.test.ts
@@ -19,9 +19,9 @@ import { strict as assert } from 'node:assert';
 import { randomUUID } from 'node:crypto';
 import { NotFoundException, Producer, SimpleConsumer } from '../../src';
 import { TransactionResolution } from 
'../../proto/apache/rocketmq/v2/definition_pb';
-import { topics, endpoints, sessionCredentials, consumerGroup, namespace } 
from '../helper';
+import { topics, endpoints, sessionCredentials, consumerGroup, namespace, 
describeIntegration } from '../helper';
 
-describe('test/producer/Producer.test.ts', () => {
+describeIntegration('test/integration/Producer.test.ts', () => {
   let producer: Producer | null = null;
   let simpleConsumer: SimpleConsumer | null = null;
   afterEach(async () => {
diff --git a/nodejs/test/consumer/SimpleConsumer.test.ts 
b/nodejs/test/integration/SimpleConsumer.test.ts
similarity index 96%
rename from nodejs/test/consumer/SimpleConsumer.test.ts
rename to nodejs/test/integration/SimpleConsumer.test.ts
index 1573f1f5..46ebe384 100644
--- a/nodejs/test/consumer/SimpleConsumer.test.ts
+++ b/nodejs/test/integration/SimpleConsumer.test.ts
@@ -21,9 +21,9 @@ import {
   SimpleConsumer, FilterExpression,
   Producer,
 } from '../../src';
-import { topics, endpoints, sessionCredentials, namespace } from '../helper';
+import { topics, endpoints, sessionCredentials, namespace, describeIntegration 
} from '../helper';
 
-describe('test/consumer/SimpleConsumer.test.ts', () => {
+describeIntegration('test/integration/SimpleConsumer.test.ts', () => {
   let producer: Producer | null = null;
   let simpleConsumer: SimpleConsumer | null = null;
   afterEach(async () => {
diff --git a/nodejs/test/message/LiteMessage.test.ts 
b/nodejs/test/message/LiteMessage.test.ts
index e58c874c..77651543 100644
--- a/nodejs/test/message/LiteMessage.test.ts
+++ b/nodejs/test/message/LiteMessage.test.ts
@@ -19,7 +19,6 @@
  * Test for Lite Message
  */
 
-import { describe, it } from 'node:test';
 import * as assert from 'node:assert';
 import { Message } from '../../src/message/Message';
 
diff --git a/nodejs/test/message/PriorityMessage.test.ts 
b/nodejs/test/message/PriorityMessage.test.ts
index b9fcb0b5..324b2598 100644
--- a/nodejs/test/message/PriorityMessage.test.ts
+++ b/nodejs/test/message/PriorityMessage.test.ts
@@ -19,7 +19,6 @@
  * Test for Priority Message
  */
 
-import { describe, it } from 'node:test';
 import * as assert from 'node:assert';
 import { Message } from '../../src/message/Message';
 import { PublishingMessage } from '../../src/message/PublishingMessage';
diff --git a/nodejs/test/message/PublishingLiteMessage.test.ts 
b/nodejs/test/message/PublishingLiteMessage.test.ts
index 4c7b8d43..290cc52b 100644
--- a/nodejs/test/message/PublishingLiteMessage.test.ts
+++ b/nodejs/test/message/PublishingLiteMessage.test.ts
@@ -19,7 +19,6 @@
  * Test for Publishing Lite Message
  */
 
-import { describe, it } from 'node:test';
 import * as assert from 'node:assert';
 import { Message } from '../../src/message/Message';
 
diff --git a/nodejs/test/metrics.test.ts b/nodejs/test/metrics.test.ts
index 7a7c7cf4..be3dc8ad 100644
--- a/nodejs/test/metrics.test.ts
+++ b/nodejs/test/metrics.test.ts
@@ -25,7 +25,6 @@
  *  - PushConsumerGaugeObserver aggregation of cached message count/bytes
  */
 
-import { describe, it } from 'node:test';
 import * as assert from 'node:assert';
 import { Metadata } from '@grpc/grpc-js';
 import { Attributes } from '@opentelemetry/api';
diff --git a/nodejs/test/producer/PublishingLoadBalancer.test.ts 
b/nodejs/test/producer/PublishingLoadBalancer.test.ts
index ca6a1535..6e2c0187 100644
--- a/nodejs/test/producer/PublishingLoadBalancer.test.ts
+++ b/nodejs/test/producer/PublishingLoadBalancer.test.ts
@@ -22,7 +22,6 @@
  * routed to different queues than the Java client.
  */
 
-import { describe, it } from 'node:test';
 import * as assert from 'node:assert';
 import { PublishingLoadBalancer } from '../../src/producer';
 import { TopicRouteData } from '../../src/route';
diff --git a/nodejs/test/route/Endpoints.test.ts 
b/nodejs/test/route/Endpoints.test.ts
index d8d692ec..79f3bc06 100644
--- a/nodejs/test/route/Endpoints.test.ts
+++ b/nodejs/test/route/Endpoints.test.ts
@@ -22,7 +22,6 @@
  * multi-address and bare-IPv6 targets correctly.
  */
 
-import { describe, it } from 'node:test';
 import * as assert from 'node:assert';
 import { Endpoints } from '../../src/route';
 import {
diff --git a/nodejs/test/route/IpNameResolver.test.ts 
b/nodejs/test/route/IpNameResolver.test.ts
index c0908d96..2f08ba17 100644
--- a/nodejs/test/route/IpNameResolver.test.ts
+++ b/nodejs/test/route/IpNameResolver.test.ts
@@ -15,7 +15,6 @@
  * limitations under the License.
  */
 
-import { describe, it } from 'node:test';
 import * as assert from 'node:assert';
 import { Endpoints } from '../../src/route';
 import { IpResolver } from '../../src/route/IpNameResolver';
diff --git a/nodejs/test/support/fakes.ts b/nodejs/test/support/fakes.ts
new file mode 100644
index 00000000..c1cb9747
--- /dev/null
+++ b/nodejs/test/support/fakes.ts
@@ -0,0 +1,108 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { Duplex } from 'node:stream';
+import type { ClientDuplexStream } from '@grpc/grpc-js';
+import * as sinon from 'sinon';
+import type { BaseClient } from '../../src/client/BaseClient';
+import type { ILogger } from '../../src/client/Logger';
+import { RpcClientManager } from '../../src/client/RpcClientManager';
+import { TelemetryCommand } from '../../proto/apache/rocketmq/v2/service_pb';
+
+export function deferred<T>() {
+  let resolve!: (value: T | PromiseLike<T>) => void;
+  let reject!: (reason?: unknown) => void;
+  const promise = new Promise<T>((res, rej) => {
+    resolve = res;
+    reject = rej;
+  });
+  return { promise, resolve, reject };
+}
+
+export function createSilentLogger() {
+  return {
+    info: sinon.stub<unknown[], void>(),
+    warn: sinon.stub<unknown[], void>(),
+    error: sinon.stub<unknown[], void>(),
+    debug: sinon.stub<unknown[], void>(),
+    close: sinon.stub<unknown[], void>(),
+  } satisfies ILogger;
+}
+
+// 不运行构造函数,避免真实 channel 和空闲回收定时器;应答通过 resolves/rejects/callsFake 设置。
+export function createFakeRpcClientManager(): 
sinon.SinonStubbedInstance<RpcClientManager> {
+  const fake = sinon.createStubInstance(RpcClientManager);
+  const asyncMethods = [
+    'queryRoute', 'heartbeat', 'sendMessage', 'queryAssignment', 
'receiveMessage',
+    'ackMessage', 'forwardMessageToDeadLetterQueue', 'pullMessage', 
'updateOffset',
+    'getOffset', 'queryOffset', 'endTransaction', 'changeInvisibleDuration',
+    'notifyClientTermination', 'recallMessage', 'syncLiteSubscription',
+  ] as const;
+  for (const method of asyncMethods) {
+    fake[method].rejects(new Error(`未配置 FakeRpcClientManager.${method}`));
+  }
+  fake.telemetry.throws(new Error('未配置 FakeRpcClientManager.telemetry'));
+  return fake;
+}
+
+// 仅注入尚未 startup 的测试客户端;先关闭构造时创建的 manager,避免遗留真实定时器。
+export function installFakeRpcClientManager(client: BaseClient, fake = 
createFakeRpcClientManager()) {
+  if (client.isRunning()) {
+    throw new Error('只能向尚未启动的客户端注入 RPC 替身');
+  }
+  client.getRpcClientManager().close();
+  Object.defineProperty(client, 'rpcClientManager', { value: fake, 
configurable: true, writable: true });
+  return fake;
+}
+
+export class FakeTelemetryStream extends Duplex {
+  readonly writes: TelemetryCommand[] = [];
+
+  constructor() {
+    super({ objectMode: true });
+  }
+
+  _read(): void {
+    // 服务端响应由测试显式发送。
+  }
+
+  _write(command: TelemetryCommand, _encoding: BufferEncoding, callback: 
(error?: Error | null) => void): void {
+    this.writes.push(command);
+    callback();
+  }
+
+  receive(command: TelemetryCommand): void {
+    this.emit('data', command);
+  }
+
+  fail(error: Error): void {
+    this.emit('error', error);
+  }
+
+  finishFromServer(): void {
+    this.emit('end');
+  }
+
+  cancel(): void {
+    this.destroy();
+  }
+
+  // 只模拟 telemetry 使用的流接口,不提供真实 gRPC metadata/status。
+  asGrpcStream(): ClientDuplexStream<TelemetryCommand, TelemetryCommand> {
+    return this as unknown as ClientDuplexStream<TelemetryCommand, 
TelemetryCommand>;
+  }
+}
diff --git a/nodejs/test/support/protobuf.ts b/nodejs/test/support/protobuf.ts
new file mode 100644
index 00000000..62f78973
--- /dev/null
+++ b/nodejs/test/support/protobuf.ts
@@ -0,0 +1,128 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { gzipSync } from 'node:zlib';
+import {
+  Broker, ClientType, Code, Digest, DigestType, Encoding, ExponentialBackoff,
+  Message, MessageQueue, MessageType, Permission, Publishing, RetryPolicy,
+  Settings, Status, Subscription, SystemProperties,
+} from '../../proto/apache/rocketmq/v2/definition_pb';
+import { Endpoints, TopicRouteData } from '../../src/route';
+import { createDuration, createResource, crc32CheckSum, md5CheckSum, 
sha1CheckSum } from '../../src/util';
+
+export function buildStatus(code = Code.OK, message = ''): Status {
+  return new Status().setCode(code).setMessage(message);
+}
+
+interface RouteOptions {
+  topic?: string;
+  namespace?: string;
+  brokers?: Array<{ name: string; id?: number; endpoints: string }>;
+  queuesPerBroker?: number;
+  brokerId?: number;
+  permission?: Permission;
+}
+
+export function buildRoute(options: RouteOptions = {}): TopicRouteData {
+  const brokers = options.brokers ?? [{ name: 'broker-0', endpoints: 
'127.0.0.1:8081' }];
+  const queues: MessageQueue[] = [];
+  for (const broker of brokers) {
+    const protoBroker = new Broker().setName(broker.name)
+      .setId(broker.id ?? options.brokerId ?? 0)
+      .setEndpoints(new Endpoints(broker.endpoints).toProtobuf());
+    for (let id = 0; id < (options.queuesPerBroker ?? 1); id++) {
+      queues.push(new MessageQueue().setId(id)
+        .setTopic(createResource(options.topic ?? 
'test-topic').setResourceNamespace(options.namespace ?? ''))
+        .setBroker(protoBroker)
+        .setPermission(options.permission ?? Permission.READ_WRITE));
+    }
+  }
+  return new TopicRouteData(queues);
+}
+
+interface MessageOptions {
+  topic?: string;
+  body?: Buffer;
+  gzip?: boolean;
+  digestType?: DigestType;
+  checksum?: string;
+  messageId?: string;
+  messageType?: MessageType;
+  receiptHandle?: string;
+  deliveryAttempt?: number;
+  tag?: string;
+  keys?: string[];
+  messageGroup?: string;
+  liteTopic?: string;
+  priority?: number;
+  properties?: Map<string, string>;
+}
+
+export function buildMessagePB(options: MessageOptions = {}): Message {
+  const rawBody = options.body ?? Buffer.from('test-body');
+  const body = options.gzip ? gzipSync(rawBody) : rawBody;
+  const digestType = options.digestType ?? DigestType.CRC32;
+  let checksum: string;
+  switch (digestType) {
+    case DigestType.CRC32: checksum = crc32CheckSum(body); break;
+    case DigestType.MD5: checksum = md5CheckSum(body); break;
+    case DigestType.SHA1: checksum = sha1CheckSum(body); break;
+    default: throw new Error(`不支持的测试 digestType: ${digestType}`);
+  }
+  const properties = new SystemProperties()
+    .setMessageId(options.messageId ?? 'test-message-id')
+    .setMessageType(options.messageType ?? MessageType.NORMAL)
+    .setReceiptHandle(options.receiptHandle ?? 'test-receipt-handle')
+    .setDeliveryAttempt(options.deliveryAttempt ?? 1)
+    .setBodyEncoding(options.gzip ? Encoding.GZIP : Encoding.IDENTITY)
+    .setBodyDigest(new 
Digest().setType(digestType).setChecksum(options.checksum ?? checksum));
+  if (options.tag !== undefined) properties.setTag(options.tag);
+  if (options.keys !== undefined) properties.setKeysList(options.keys);
+  if (options.messageGroup !== undefined) 
properties.setMessageGroup(options.messageGroup);
+  if (options.liteTopic !== undefined) 
properties.setLiteTopic(options.liteTopic);
+  if (options.priority !== undefined) properties.setPriority(options.priority);
+  const message = new Message().setTopic(createResource(options.topic ?? 
'test-topic'))
+    .setBody(body)
+    .setSystemProperties(properties);
+  for (const [ key, value ] of options.properties ?? []) {
+    message.getUserPropertiesMap().set(key, value);
+  }
+  return message;
+}
+
+export function buildSettings(options: {
+  clientType?: ClientType;
+  requestTimeout?: number;
+  retryPolicy?: RetryPolicy;
+  publishing?: Publishing;
+  subscription?: Subscription;
+} = {}): Settings {
+  const retryPolicy = options.retryPolicy ?? new 
RetryPolicy().setMaxAttempts(3)
+    .setExponentialBackoff(new ExponentialBackoff()
+      .setInitial(createDuration(1000)).setMax(createDuration(10000))
+      .setMultiplier(2));
+  const settings = new Settings().setClientType(options.clientType ?? 
ClientType.PRODUCER)
+    .setRequestTimeout(createDuration(options.requestTimeout ?? 3000))
+    .setBackoffPolicy(retryPolicy);
+  if (options.subscription) {
+    settings.setSubscription(options.subscription);
+  } else {
+    settings.setPublishing(options.publishing ?? new Publishing()
+      .setMaxBodySize(4 * 1024 * 1024).setValidateMessageType(true));
+  }
+  return settings;
+}
diff --git a/nodejs/test/support/support.test.ts 
b/nodejs/test/support/support.test.ts
new file mode 100644
index 00000000..39338bd7
--- /dev/null
+++ b/nodejs/test/support/support.test.ts
@@ -0,0 +1,167 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { strict as assert } from 'node:assert';
+import * as sinon from 'sinon';
+import { Metadata } from '@grpc/grpc-js';
+import { ClientType, Code, DigestType, Permission, Subscription } from 
'../../proto/apache/rocketmq/v2/definition_pb';
+import { QueryRouteRequest, QueryRouteResponse, TelemetryCommand } from 
'../../proto/apache/rocketmq/v2/service_pb';
+import { Producer } from '../../src/producer';
+import { MessageView } from '../../src/message';
+import { Endpoints } from '../../src/route';
+import { createDuration } from '../../src/util';
+import { createFakeRpcClientManager, createSilentLogger, deferred, 
FakeTelemetryStream, installFakeRpcClientManager } from './fakes';
+import { buildMessagePB, buildRoute, buildSettings, buildStatus } from 
'./protobuf';
+
+describe('test/support', () => {
+  afterEach(() => sinon.restore());
+
+  it('deferred allows explicit resolve and reject', async () => {
+    const success = deferred<number>();
+    success.resolve(42);
+    assert.strictEqual(await success.promise, 42);
+    const failure = deferred<void>();
+    const error = new Error('controlled rejection');
+    const assertion = assert.rejects(failure.promise, reason => reason === 
error);
+    failure.reject(error);
+    await assertion;
+  });
+
+  it('silent logger records arguments without writing logs', () => {
+    const logger = createSilentLogger();
+    logger.info('topic=%s', 'topic-a');
+    logger.warn('retry');
+    logger.error(new Error('failure'));
+    logger.debug('debug');
+    logger.close();
+    sinon.assert.calledWithExactly(logger.info, 'topic=%s', 'topic-a');
+    for (const level of [ 'warn', 'error', 'debug', 'close' ] as const) {
+      sinon.assert.calledOnce(logger[level]);
+    }
+  });
+
+  it('RPC fake supports responses, rejections, deferred calls and call 
records', async () => {
+    const fake = createFakeRpcClientManager();
+    const endpoints = new Endpoints('127.0.0.1:8081');
+    const request = new QueryRouteRequest();
+    const response = new QueryRouteResponse().setStatus(buildStatus());
+    const held = deferred<QueryRouteResponse>();
+    fake.queryRoute.onFirstCall().resolves(response);
+    fake.queryRoute.onSecondCall().rejects(new Error('route failed'));
+    fake.queryRoute.onThirdCall().callsFake(() => held.promise);
+    assert.strictEqual(await fake.queryRoute(endpoints, request, 3000), 
response);
+    await assert.rejects(() => fake.queryRoute(endpoints, request, 3000), 
/route failed/);
+    const waiting = fake.queryRoute(endpoints, request, 3000);
+    held.resolve(response);
+    assert.strictEqual(await waiting, response);
+    sinon.assert.calledThrice(fake.queryRoute);
+    assert.deepStrictEqual(fake.queryRoute.firstCall.args, [ endpoints, 
request, 3000 ]);
+    await assert.rejects(() => fake.sendMessage(endpoints, null as never, 
3000), /未配置/);
+    assert.throws(() => fake.telemetry(endpoints, new Metadata()), /未配置/);
+  });
+
+  it('RPC injection closes the real manager and is used by the client', async 
() => {
+    const client = new Producer({ endpoints: '127.0.0.1:8081', namespace: '', 
logger: createSilentLogger() });
+    const original = client.getRpcClientManager();
+    const closed = sinon.spy(original, 'close');
+    try {
+      const fake = installFakeRpcClientManager(client);
+      sinon.assert.calledOnce(closed);
+      assert.strictEqual(client.getRpcClientManager(), fake);
+      await client.shutdown();
+      sinon.assert.calledOnce(fake.close);
+    } finally {
+      original.close();
+      closed.restore();
+    }
+  });
+
+  it('telemetry fake records writes and exposes data, error and server end 
events', () => {
+    const stream = new FakeTelemetryStream();
+    const command = new TelemetryCommand().setSettings(buildSettings());
+    const data = sinon.spy();
+    const error = sinon.spy();
+    const end = sinon.spy();
+    stream.on('data', data).on('error', error).on('end', end);
+    stream.write(command);
+    stream.receive(command);
+    const failure = new Error('stream failed');
+    stream.fail(failure);
+    stream.finishFromServer();
+    assert.deepStrictEqual(stream.writes, [ command ]);
+    sinon.assert.calledWithExactly(data, command);
+    sinon.assert.calledWithExactly(error, failure);
+    sinon.assert.calledOnce(end);
+    assert.strictEqual(stream.asGrpcStream(), stream);
+    stream.end();
+    assert.ok(stream.writableEnded);
+    stream.cancel();
+    assert.ok(stream.destroyed);
+  });
+
+  it('route builder keeps broker ids, queue ids and permissions independently 
configurable', () => {
+    const route = buildRoute({
+      topic: 'topic-a', namespace: 'ns', queuesPerBroker: 2, permission: 
Permission.READ,
+      brokers: [
+        { name: 'master', id: 0, endpoints: '127.0.0.1:8081' },
+        { name: 'slave', id: 1, endpoints: '127.0.0.1:8082' },
+      ],
+    });
+    assert.deepStrictEqual(route.messageQueues.map(mq => [ mq.broker.id, 
mq.queueId ]), [[ 0, 0 ], [ 0, 1 ], [ 1, 0 ], [ 1, 1 ]]);
+    assert.ok(route.messageQueues.every(mq => mq.permission === 
Permission.READ && mq.topic.name === 'topic-a'));
+    assert.strictEqual(route.getTotalEndpoints().length, 2);
+    assert.ok(buildRoute({ brokers: [] }).isEmpty());
+  });
+
+  for (const digestType of [ DigestType.CRC32, DigestType.MD5, DigestType.SHA1 
]) {
+    it(`message builder creates a decodable compressed message with digest 
${digestType}`, () => {
+      const body = Buffer.from('body');
+      const message = new MessageView(buildMessagePB({ body, gzip: true, 
digestType, priority: 0,
+        liteTopic: 'lite-a', keys: [ 'key-a' ], properties: new Map([[ 'k', 
'v' ]]) }), buildRoute().messageQueues[0]);
+      assert.deepStrictEqual(message.body, body);
+      assert.ok(!message.corrupted);
+      assert.strictEqual(message.liteTopic, 'lite-a');
+      assert.strictEqual(message.priority, 0);
+      assert.strictEqual(message.properties.get('k'), 'v');
+      assert.deepStrictEqual(message.keys, [ 'key-a' ]);
+    });
+  }
+
+  it('message builder supports explicit corruption without omitting required 
fields', () => {
+    const message = new MessageView(buildMessagePB({ checksum: 'invalid' }), 
buildRoute().messageQueues[0]);
+    assert.strictEqual(message.corrupted, true);
+    assert.strictEqual(buildStatus(Code.BAD_REQUEST, 'bad 
input').getMessage(), 'bad input');
+  });
+
+  it('settings builder supplies usable publishing and subscription settings', 
() => {
+    const settings = buildSettings();
+    assert.strictEqual(settings.getPublishing()?.getMaxBodySize(), 4 * 1024 * 
1024);
+    assert.strictEqual(settings.getBackoffPolicy()?.getMaxAttempts(), 3);
+    const subscription = new 
Subscription().setReceiveBatchSize(10).setLongPollingTimeout(createDuration(5000));
+    assert.strictEqual(buildSettings({ clientType: ClientType.SIMPLE_CONSUMER, 
subscription }).getSubscription(), subscription);
+  });
+
+  it('fake timers control delayed work and can be restored', async () => {
+    const clock = sinon.useFakeTimers();
+    const pending = deferred<void>();
+    setTimeout(() => pending.resolve(), 30000);
+    assert.strictEqual(clock.countTimers(), 1);
+    await clock.tickAsync(30000);
+    await pending.promise;
+    assert.strictEqual(clock.countTimers(), 0);
+  });
+});
diff --git a/nodejs/test/util/Semaphore.test.ts 
b/nodejs/test/util/Semaphore.test.ts
index 2884a98d..ee897a9e 100644
--- a/nodejs/test/util/Semaphore.test.ts
+++ b/nodejs/test/util/Semaphore.test.ts
@@ -15,7 +15,6 @@
  * limitations under the License.
  */
 
-import { describe, it } from 'node:test';
 import * as assert from 'node:assert';
 import { Semaphore } from '../../src/util/Semaphore';
 

Reply via email to