test: you can now supply promises for values when mocking RPC subscriptions (#24920)

This commit is contained in:
Steven Luscher 2022-05-02 17:02:35 -07:00 committed by GitHub
parent eff59193db
commit dd8295981b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 19 additions and 5 deletions

View File

@ -13,10 +13,11 @@ type RpcResponse = {
context: { context: {
slot: number; slot: number;
}; };
value: any; value: any | Promise<any>;
}; };
const mockRpcSocket: Array<[RpcRequest, RpcResponse]> = []; const mockRpcSocket: Array<[RpcRequest, RpcResponse | Promise<RpcResponse>]> =
[];
const sandbox = createSandbox(); const sandbox = createSandbox();
export const mockRpcMessage = ({ export const mockRpcMessage = ({
@ -26,7 +27,7 @@ export const mockRpcMessage = ({
}: { }: {
method: string; method: string;
params: Array<any>; params: Array<any>;
result: any; result: any | Promise<any>;
}) => { }) => {
mockRpcSocket.push([ mockRpcSocket.push([
{method, params}, {method, params},
@ -62,6 +63,14 @@ export const restoreRpcWebSocket = (connection: Connection) => {
sandbox.restore(); 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 { class MockClient {
client: LiveClient; client: LiveClient;
mockOpen = false; mockOpen = false;
@ -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); expect(mockRpcSocket.length).to.be.at.least(1);
const [mockRequest, mockResponse] = mockRpcSocket.shift() as [ const [mockRequest, mockResponse] = mockRpcSocket.shift() as [
RpcRequest, RpcRequest,
@ -103,7 +112,12 @@ class MockClient {
let id = ++this.subscriptionCounter; let id = ++this.subscriptionCounter;
const response = { const response = {
subscription: id, subscription: id,
result: mockResponse, result: {
...mockResponse,
value: isPromise(mockResponse.value)
? await mockResponse.value
: mockResponse.value,
},
}; };
setImmediate(() => { setImmediate(() => {