From dd8295981b10ecb8b42721ce9e07e9425a066250 Mon Sep 17 00:00:00 2001 From: Steven Luscher Date: Mon, 2 May 2022 17:02:35 -0700 Subject: [PATCH] test: you can now supply promises for values when mocking RPC subscriptions (#24920) --- web3.js/test/mocks/rpc-websockets.ts | 24 +++++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/web3.js/test/mocks/rpc-websockets.ts b/web3.js/test/mocks/rpc-websockets.ts index ba8a82ea2..eae2c4a7c 100644 --- a/web3.js/test/mocks/rpc-websockets.ts +++ b/web3.js/test/mocks/rpc-websockets.ts @@ -13,10 +13,11 @@ type RpcResponse = { context: { slot: number; }; - value: any; + value: any | Promise; }; -const mockRpcSocket: Array<[RpcRequest, RpcResponse]> = []; +const mockRpcSocket: Array<[RpcRequest, RpcResponse | Promise]> = + []; const sandbox = createSandbox(); export const mockRpcMessage = ({ @@ -26,7 +27,7 @@ export const mockRpcMessage = ({ }: { method: string; params: Array; - result: any; + result: any | Promise; }) => { mockRpcSocket.push([ {method, params}, @@ -62,6 +63,14 @@ export const restoreRpcWebSocket = (connection: Connection) => { sandbox.restore(); }; +function isPromise(obj: PromiseLike | T): obj is PromiseLike { + return ( + !!obj && + (typeof obj === 'object' || typeof obj === 'function') && + typeof (obj as any).then === 'function' + ); +} + class MockClient { client: LiveClient; mockOpen = false; @@ -85,7 +94,7 @@ class MockClient { } } - call(method: string, params: Array): Promise { + async call(method: string, params: Array): Promise { expect(mockRpcSocket.length).to.be.at.least(1); const [mockRequest, mockResponse] = mockRpcSocket.shift() as [ RpcRequest, @@ -103,7 +112,12 @@ class MockClient { let id = ++this.subscriptionCounter; const response = { subscription: id, - result: mockResponse, + result: { + ...mockResponse, + value: isPromise(mockResponse.value) + ? await mockResponse.value + : mockResponse.value, + }, }; setImmediate(() => {