Skip to content

Commit

Permalink
test: you can now supply promises for values when mocking RPC subscri…
Browse files Browse the repository at this point in the history
…ptions (solana-labs#24920)
  • Loading branch information
steveluscher authored and jeffwashington committed Jun 29, 2022
1 parent 4c56642 commit 13b2985
Showing 1 changed file with 19 additions and 5 deletions.
24 changes: 19 additions & 5 deletions web3.js/test/mocks/rpc-websockets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,11 @@ type RpcResponse = {
context: {
slot: number;
};
value: any;
value: any | Promise<any>;
};

const mockRpcSocket: Array<[RpcRequest, RpcResponse]> = [];
const mockRpcSocket: Array<[RpcRequest, RpcResponse | Promise<RpcResponse>]> =
[];
const sandbox = createSandbox();

export const mockRpcMessage = ({
Expand All @@ -26,7 +27,7 @@ export const mockRpcMessage = ({
}: {
method: string;
params: Array<any>;
result: any;
result: any | Promise<any>;
}) => {
mockRpcSocket.push([
{method, params},
Expand Down Expand Up @@ -62,6 +63,14 @@ export const restoreRpcWebSocket = (connection: Connection) => {
sandbox.restore();
};

function isPromise<T>(obj: PromiseLike<T> | T): obj is PromiseLike<T> {
return (
!!obj &&
(typeof obj === 'object' || typeof obj === 'function') &&
typeof (obj as any).then === 'function'
);
}

class MockClient {
client: LiveClient;
mockOpen = false;
Expand All @@ -85,7 +94,7 @@ class MockClient {
}
}

call(method: string, params: Array<any>): Promise<Object> {
async call(method: string, params: Array<any>): Promise<Object> {
expect(mockRpcSocket.length).to.be.at.least(1);
const [mockRequest, mockResponse] = mockRpcSocket.shift() as [
RpcRequest,
Expand All @@ -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(() => {
Expand Down

0 comments on commit 13b2985

Please sign in to comment.