Files
api/packages/rpc-provider/test/mockWs.ts
T
Jaco 557283a3d1 Struct decoding error messaging (#3425)
* Struct decoding error messaging

* Error adjust

* Tests

* Bump common, use stringify

* Linting

* Adjust

* Bumps

* Rebump

* Assert cleanups

* Don't modify original value on encoding

* util bump, fixe compact encoding
2021-04-22 15:02:54 +02:00

90 lines
1.9 KiB
TypeScript

// Copyright 2017-2021 @polkadot/rpc-provider authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { Server, WebSocket } from 'mock-socket';
import { stringify } from '@polkadot/util';
interface Scope {
body: { [index: string]: Record<string, any> };
requests: number;
server: Server;
done: any;
}
interface ErrorDef {
id: number;
error: {
code: number;
message: string;
};
}
interface ReplyDef {
id: number;
reply: {
result: unknown;
};
}
global.WebSocket = WebSocket;
export const TEST_WS_URL = 'ws://localhost:9955';
// should be JSONRPC def return
function createError ({ error: { code, message }, id }: ErrorDef): any {
return {
error: {
code,
message
},
id,
jsonrpc: '2.0'
};
}
// should be JSONRPC def return
function createReply ({ id, reply: { result } }: ReplyDef): any {
return {
id,
jsonrpc: '2.0',
result
};
}
// scope definition returned
export function mockWs (requests: ({ method: string } & ErrorDef)[], wsUrl: string = TEST_WS_URL): Scope {
const server = new Server(wsUrl);
let requestCount = 0;
const scope: Scope = {
body: {},
done: (): void => {
server.stop((): void => {
// ignore
});
},
requests: 0,
server
};
server.on('connection', (socket): void => {
// FIXME This whole any mess is a mess
socket.on('message', (body: any): void => {
const request: any = requests[requestCount];
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-member-access
const response: any = request.error
? createError(request)
: createReply(request);
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-member-access
scope.body[request.method] = body;
requestCount++;
socket.send(stringify(response));
});
});
return scope;
}