mirror of
https://github.com/zkitter/json-rpc-engine.git
synced 2026-01-10 07:37:54 -05:00
Migrates all tests to Jest and TypeScript per the module template. Care was taken to modify the existing tests as little as possible. Therefore, the tests unfortunately make prodigious use of casts to `any`. Nevertheless, to minimize such casts, a pair of assertion type guards were added for successful and failed JSON-RPC responses. They use the existing boolean type guards under the hood, and are fully tested. Assertion type guards are tremendously helpful in situations like this, where boolean type guards don't help since e.g. `expect(typeGuard(value)).toBe(true);` doesn't tell TypeScript anything, and we have lint rules preventing us from calling `expect` conditionally.
54 lines
1.5 KiB
TypeScript
54 lines
1.5 KiB
TypeScript
import {
|
|
JsonRpcEngine,
|
|
createScaffoldMiddleware,
|
|
JsonRpcMiddleware,
|
|
assertIsJsonRpcSuccess,
|
|
assertIsJsonRpcFailure,
|
|
} from '.';
|
|
|
|
describe('createScaffoldMiddleware', () => {
|
|
it('basic middleware test', async () => {
|
|
const engine = new JsonRpcEngine();
|
|
|
|
const scaffold: Record<
|
|
string,
|
|
string | JsonRpcMiddleware<unknown, unknown>
|
|
> = {
|
|
method1: 'foo',
|
|
method2: (_req, res, _next, end) => {
|
|
res.result = 42;
|
|
end();
|
|
},
|
|
method3: (_req, res, _next, end) => {
|
|
res.error = new Error('method3');
|
|
end();
|
|
},
|
|
};
|
|
|
|
engine.push(createScaffoldMiddleware(scaffold));
|
|
engine.push((_req, res, _next, end) => {
|
|
res.result = 'passthrough';
|
|
end();
|
|
});
|
|
|
|
const payload = { id: 1, jsonrpc: '2.0' as const };
|
|
|
|
const response1 = await engine.handle({ ...payload, method: 'method1' });
|
|
const response2 = await engine.handle({ ...payload, method: 'method2' });
|
|
const response3 = await engine.handle({ ...payload, method: 'method3' });
|
|
const response4 = await engine.handle({ ...payload, method: 'unknown' });
|
|
|
|
assertIsJsonRpcSuccess(response1);
|
|
expect(response1.result).toStrictEqual('foo');
|
|
|
|
assertIsJsonRpcSuccess(response2);
|
|
expect(response2.result).toStrictEqual(42);
|
|
|
|
assertIsJsonRpcFailure(response3);
|
|
expect(response3.error.message).toStrictEqual('method3');
|
|
|
|
assertIsJsonRpcSuccess(response4);
|
|
expect(response4.result).toStrictEqual('passthrough');
|
|
});
|
|
});
|