2018-08-24 10:39:51 -07:00
|
|
|
// @flow
|
|
|
|
|
2018-08-24 17:14:58 -07:00
|
|
|
import fetch from 'node-fetch';
|
|
|
|
|
2018-08-24 10:39:51 -07:00
|
|
|
type RpcRequest = {
|
|
|
|
method: string;
|
2018-08-24 17:14:58 -07:00
|
|
|
params?: Array<any>;
|
2018-08-24 10:39:51 -07:00
|
|
|
};
|
|
|
|
|
|
|
|
type RpcResponseError = {
|
|
|
|
message: string;
|
|
|
|
}
|
|
|
|
type RpcResponseResult = boolean | string | number;
|
|
|
|
type RpcResponse = {
|
|
|
|
error: ?RpcResponseError;
|
|
|
|
result: ?RpcResponseResult;
|
|
|
|
};
|
|
|
|
|
|
|
|
export const mockRpc: Array<[string, RpcRequest, RpcResponse]> = [];
|
|
|
|
|
2018-08-24 10:54:02 -07:00
|
|
|
// Suppress lint: 'JestMockFn' is not defined
|
|
|
|
// eslint-disable-next-line no-undef
|
2018-08-24 10:39:51 -07:00
|
|
|
const mock: JestMockFn<any, any> = jest.fn(
|
|
|
|
(fetchUrl, fetchOptions) => {
|
2018-08-24 17:14:58 -07:00
|
|
|
// Define DOITLIVE in the environment to test against the real full node
|
|
|
|
// identified by `url` instead of using the mock
|
|
|
|
if (process.env.DOITLIVE) {
|
|
|
|
console.log(`Note: node-fetch mock is disabled, testing live against ${fetchUrl}`);
|
|
|
|
return fetch(fetchUrl, fetchOptions);
|
|
|
|
}
|
|
|
|
|
2018-08-24 10:39:51 -07:00
|
|
|
expect(mockRpc.length).toBeGreaterThanOrEqual(1);
|
|
|
|
const [mockUrl, mockRequest, mockResponse] = mockRpc.shift();
|
|
|
|
|
|
|
|
expect(fetchUrl).toBe(mockUrl);
|
|
|
|
expect(fetchOptions).toMatchObject({
|
|
|
|
method: 'POST',
|
|
|
|
headers: {
|
|
|
|
'Content-Type': 'application/json'
|
|
|
|
},
|
|
|
|
});
|
|
|
|
expect(fetchOptions.body).toBeDefined();
|
|
|
|
|
|
|
|
const body = JSON.parse(fetchOptions.body);
|
|
|
|
expect(body).toMatchObject(Object.assign(
|
|
|
|
{},
|
|
|
|
{
|
|
|
|
jsonrpc: '2.0',
|
|
|
|
method: 'invalid',
|
|
|
|
},
|
|
|
|
mockRequest
|
|
|
|
));
|
|
|
|
|
|
|
|
const response = Object.assign(
|
|
|
|
{},
|
|
|
|
{
|
|
|
|
jsonrpc: '2.0',
|
|
|
|
id: body.id,
|
|
|
|
error: {
|
|
|
|
message: 'invalid error message',
|
|
|
|
},
|
|
|
|
result: 'invalid response',
|
|
|
|
},
|
|
|
|
mockResponse,
|
|
|
|
);
|
|
|
|
return {
|
|
|
|
text: () => {
|
|
|
|
return Promise.resolve(JSON.stringify(response));
|
|
|
|
},
|
|
|
|
};
|
|
|
|
}
|
|
|
|
);
|
|
|
|
|
|
|
|
export default mock;
|