ts-mockito#capture TypeScript Examples
The following examples show how to use
ts-mockito#capture.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: server.spec.ts From xrp-api with MIT License | 6 votes |
describe('Server', () => {
it('logs in green when a request succeeds', async () => {
await request(mockApp)
.get('/v3/ping')
.expect(200);
expect(capture(mockedDebuglog.log).first()).to.deep.equal([ '\u001b[32m%s\u001b[0m', '/v3/ping response validated' ]);
});
it('logs in red when a request fails', async () => {
await request(mockApp)
.get('/v3/DOES-NOT-EXIST')
.expect(404);
expect(capture(mockedDebuglog.log).first()).to.deep.equal([ '\u001b[31m%s\u001b[0m', 'GET /v3/DOES-NOT-EXIST 404' ]);
});
it('returns an error if path does not start with /v3', async () => {
await request(mockApp)
.get('/DOES-NOT-EXIST')
.expect(404);
expect(capture(mockedDebuglog.log).first()).to.deep.equal([ '\u001b[31m%s\u001b[0m', 'GET /DOES-NOT-EXIST 404' ]);
});
});
Example #2
Source File: info.spec.ts From xrp-api with MIT License | 5 votes |
describe(path, () => {
it('GET - returns account info', (done) => {
sinon.stub(rippleApi, 'isConnected').returns(true);
sinon.stub(rippleApi, 'request').resolves(getAccountInfoFixture);
request(mockApp)
.get(path)
.expect(200)
.expect(res => {
expect(res.text.length).to.be.greaterThan(400).lessThan(500);
expect(capture(mockedDebuglog.log).first()).to.deep.equal(["\u001b[32m%s\u001b[0m","/v3/accounts/{address}/info response validated"]);
})
.end(done);
});
it('GET - passes along ledger_index', (done) => {
sinon.stub(rippleApi, 'isConnected').returns(true);
sinon.stub(rippleApi, 'request').withArgs('account_info', {
// Use camelcase for rippled API
ledger_index: 'validated', // eslint-disable-line @typescript-eslint/camelcase
account: '{address}'
}).resolves(Object.assign({}, getAccountInfoFixture, {validated: true}));
request(mockApp)
.get(path + '?ledger_index=validated')
.expect(200)
.expect(res => {
expect(res.text.length).to.be.greaterThan(400).lessThan(500);
expect(res.body.validated).to.equal(true);
expect(capture(mockedDebuglog.log).first()).to.deep.equal(["\u001b[32m%s\u001b[0m","/v3/accounts/{address}/info response validated"]);
})
.end(done);
});
it('GET - with invalid ledger_index - returns 400 bad request', (done) => {
sinon.stub(rippleApi, 'isConnected').returns(true);
sinon.stub(rippleApi, 'request')
.rejects({name: 'RippledError', data: accountInfoLedgerIndexFooFixture});
request(mockApp)
.get(path + '?ledger_index=foo')
.expect(400)
.expect(res => {
expect(JSON.parse(res.text)).to.eql(accountInfoLedgerIndexFooResponseFixture);
})
.end(done);
});
it('GET - fails validation when response is invalid', (done) => {
sinon.stub(rippleApi, 'isConnected').returns(true);
const getAccountInfoResponse = Object.assign({}, getAccountInfoFixture);
// For testing only:
(getAccountInfoResponse.account_data as any).foo = 'bar'; // eslint-disable-line @typescript-eslint/no-explicit-any
sinon.stub(rippleApi, 'request').resolves(getAccountInfoResponse);
request(mockApp)
.get(path)
.expect(200)
.expect(() => {
expect(capture(mockedDebuglog.log).byCallIndex(0)).to.deep.equal(["\u001b[31m%s\u001b[0m","/v3/accounts/{address}/info validation:",{"message":"The response was not valid.","errors":[{"path":"account_data","errorCode":"additionalProperties.openapi.responseValidation","message":"should NOT have additional properties"}]}]);
})
.end(done);
});
});
Example #3
Source File: info.spec.ts From xrp-api with MIT License | 5 votes |
describe(path, () => {
it('GET - returns server info', (done) => {
sinon.stub(rippleApi, 'isConnected').returns(true);
sinon.stub(rippleApi, 'getServerInfo').resolves(getServerInfoFixture);
request(mockApp)
.get(path)
.expect(200)
.expect(res => {
expect(res.text.length).to.be.greaterThan(1900).lessThan(2000);
expect(capture(mockedDebuglog.log).first()).to.deep.equal(["\u001b[32m%s\u001b[0m","response validated"]);
})
.end(done);
});
it('GET - when not connected, returns server version and empty rippled_servers array', (done) => {
sinon.stub(rippleApi, 'isConnected').returns(false);
const getServerInfoStub = sinon.stub(rippleApi, 'getServerInfo');
request(mockApp)
.get(path)
.expect(200)
.expect(res => {
const obj = JSON.parse(res.text);
expect(obj.server_version).to.be.a('string');
expect(obj.rippled_servers).to.be.an('array').that.is.empty;
expect(res.text.length).to.be.greaterThan(40).lessThan(50);
sinon.assert.notCalled(getServerInfoStub);
})
.end(done);
});
it('GET - fails validation when response is invalid', (done) => {
sinon.stub(rippleApi, 'isConnected').returns(true);
sinon.stub(rippleApi, 'getServerInfo').resolves(Object.assign({}, getServerInfoFixture, {foo: 'bar'}));
request(mockApp)
.get(path)
.expect(200)
.expect(() => {
expect(capture(mockedDebuglog.log).first()).to.deep.equal(["\u001b[31m%s\u001b[0m","validation:",{"message":"The response was not valid.","errors":[{"path":"rippled_servers[0]","errorCode":"additionalProperties.openapi.responseValidation","message":"should NOT have additional properties"}]}]);
})
.end(done);
});
});
Example #4
Source File: multicall.service.test.ts From multicall with MIT License | 4 votes |
describe('MultiCallService', () => {
const multiCallAddress = '0x001';
let multiCallService: MultiCallService;
let connector: ProviderConnector;
beforeEach(() => {
connector = mock<ProviderConnector>();
multiCallService = new MultiCallService(
instance(connector),
multiCallAddress
);
});
beforeEach(() => {
when(connector.contractEncodeABI(anything(), anything(), anything(), anything())).thenCall((
_: unknown, __: string, methodName: string, params: unknown[],
) => {
return {methodName, params};
});
when(connector.ethCall(anything(), anything(), anything())).thenCall((
_: unknown, callData: {methodName: string, params: unknown[]}
) => {
return callData;
});
});
describe('callByGasLimit() full successful multicall', () => {
beforeEach(() => {
when(connector.decodeABIParameterList(anything(), anything())).thenCall((
_: unknown, callData: {methodName: string, params: unknown[]}
) => {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
return {results: callData.params[0], lastSuccessIndex: callData.params[0].length};
});
});
it('test', async () => {
const gasLimit = 410;
const requests: MultiCallRequestWithGas[] = [
{to: '01', data: '01', gas: 100},
{to: '02', data: '02', gas: 100},
{to: '03', data: '03', gas: 100},
{to: '04', data: '04', gas: 100},
{to: '05', data: '05', gas: 100},
{to: '06', data: '06', gas: 100},
{to: '07', data: '07', gas: 100},
{to: '08', data: '08', gas: 100},
{to: '09', data: '09', gas: 100},
{to: '10', data: '10', gas: 100},
];
const result = await multiCallService.callByGasLimit(requests, gasLimit, {
...defaultParamsWithGas,
maxChunkSize: 3,
});
expect(result).toEqual(requests.map(r => ({to: r.to, data: r.data})));
});
});
describe('callByGasLimit() multicall with errors', () => {
function getLastSuccessIndex(requests: MultiCallRequest[]): number {
// lastSuccessIndex = 1, it means that only 01, 02 responses were successful
if (requests.map(i => i.data).join('') === '010203') {
return 1;
}
// lastSuccessIndex = 1, it means that only 04, 05 responses were successful
if (requests.map(i => i.data).join('') === '040506') {
return 1;
}
// lastSuccessIndex = 0, it means that only 7 responses were successful
if (requests.map(i => i.data).join('') === '070809') {
return 0;
}
return requests.length - 1;
}
beforeEach(() => {
when(connector.decodeABIParameterList(anything(), anything())).thenCall((
_: unknown, callData: {methodName: string, params: unknown[]}
) => {
const results = callData.params[0] as MultiCallRequest[];
return {results, lastSuccessIndex: getLastSuccessIndex(results)};
});
});
it('test', async () => {
const gasLimit = 300;
const requests: MultiCallRequestWithGas[] = [
{to: '01', data: '01', gas: 100},
{to: '02', data: '02', gas: 100},
{to: '03', data: '03', gas: 100},
{to: '04', data: '04', gas: 100},
{to: '05', data: '05', gas: 100},
{to: '06', data: '06', gas: 100},
{to: '07', data: '07', gas: 100},
{to: '08', data: '08', gas: 100},
{to: '09', data: '09', gas: 100},
{to: '10', data: '10', gas: 100},
];
const expectedRequestsByChunks = [
[
{to: '01', data: '01'},
{to: '02', data: '02'},
{to: '03', data: '03'},
],
[
{to: '04', data: '04'},
{to: '05', data: '05'},
{to: '06', data: '06'},
],
[
{to: '07', data: '07'},
{to: '08', data: '08'},
{to: '09', data: '09'},
],
[
{to: '10', data: '10'},
],
[
{to: '03', data: '03'},
{to: '06', data: '06'},
],
[
{to: '08', data: '08'},
{to: '09', data: '09'},
],
];
const result = await multiCallService.callByGasLimit(requests, gasLimit, {
...defaultParamsWithGas,
maxChunkSize: 3,
});
const ethCalls = capture(connector.ethCall);
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const ethCallArguments = [0,1,2,3,4,5].map(index => ethCalls.byCallIndex(index)[1]['params'][0]);
expect(ethCallArguments).toEqual(expectedRequestsByChunks);
expect(result).toEqual(requests.map(r => ({to: r.to, data: r.data})));
});
});
});
Example #5
Source File: settings.spec.ts From xrp-api with MIT License | 4 votes |
describe(path, () => {
it('GET settings - returns account settings', (done) => {
sinon.stub(rippleApi, 'isConnected').returns(true);
const getSettingsResponse = {
"requireDestinationTag": true,
"disallowIncomingXRP": true,
"emailHash": "23463B99B62A72F26ED677CC556C44E8",
"walletLocator": "00000000000000000000000000000000000000000000000000000000DEADBEEF",
"domain": "example.com",
"transferRate": 1.002,
"tickSize": 5,
"signers": {
"threshold": 3,
"weights": [
{
"address": "rpHit3GvUR1VSGh2PXcaaZKEEUnCVxWU2i",
"weight": 1
}, {
"address": "rN4oCm1c6BQz6nru83H52FBSpNbC9VQcRc",
"weight": 1
}, {
"address": "rJ8KhCi67VgbapiKCQN3r1ZA6BMUxUvvnD",
"weight": 1
}
]
}
};
sinon.stub(rippleApi, 'getSettings').resolves(getSettingsResponse);
request(mockApp)
.get(path.replace('{address}', 'r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59'))
.expect(200)
.expect(getSettingsResponse)
.expect(() => {
expect(capture(mockedDebuglog.log).first()).to.deep.equal(["\u001b[32m%s\u001b[0m","/v3/accounts/r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59/settings response validated"]);
})
.end(done);
});
it('GET settings - passes along ledger_index', (done) => {
sinon.stub(rippleApi, 'isConnected').returns(true);
const getSettingsResponse = {
"requireDestinationTag": true,
"disallowIncomingXRP": true,
"emailHash": "23463B99B62A72F26ED677CC556C44E8",
"walletLocator": "00000000000000000000000000000000000000000000000000000000DEADBEEF",
"domain": "example.com",
"transferRate": 1.002,
"tickSize": 5,
"signers": {
"threshold": 3,
"weights": [
{
"address": "rpHit3GvUR1VSGh2PXcaaZKEEUnCVxWU2i",
"weight": 1
}, {
"address": "rN4oCm1c6BQz6nru83H52FBSpNbC9VQcRc",
"weight": 1
}, {
"address": "rJ8KhCi67VgbapiKCQN3r1ZA6BMUxUvvnD",
"weight": 1
}
]
}
};
sinon.stub(rippleApi, 'getSettings').withArgs('r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59', {
ledgerVersion: 'validated'
} as any).resolves(getSettingsResponse); // eslint-disable-line @typescript-eslint/no-explicit-any
request(mockApp)
.get(path.replace('{address}', 'r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59') + '?ledger_index=validated')
.expect(200)
.expect(getSettingsResponse)
.expect(() => {
expect(capture(mockedDebuglog.log).first()).to.deep.equal(["\u001b[32m%s\u001b[0m","/v3/accounts/r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59/settings response validated"]);
})
.end(done);
});
it('GET settings - invalid response from RippleAPI triggers response validation error', (done) => {
sinon.stub(rippleApi, 'isConnected').returns(true);
const invalidGetSettingsResponse = {
foo: 'bar'
};
sinon.stub(rippleApi, 'getSettings').resolves(invalidGetSettingsResponse as any); // eslint-disable-line @typescript-eslint/no-explicit-any
request(mockApp)
.get(path)
.expect(200)
.expect((x) => {
expect(capture(mockedDebuglog.log).first()).to.deep.equal(["\u001b[31m%s\u001b[0m","/v3/accounts/{address}/settings validation:",{"message":"The response was not valid.","errors":[{"path":"response","errorCode":"additionalProperties.openapi.responseValidation","message":"should NOT have additional properties"}]}]);
})
.end(done);
});
it('GET settings - request fails for X-address with tag', (done) => {
sinon.stub(rippleApi, 'isConnected').returns(true);
const invalidGetSettingsResponse = {
foo: 'bar'
};
sinon.stub(rippleApi, 'request').resolves(invalidGetSettingsResponse);
request(mockApp)
.get(path.replace('{address}', 'XV5sbjUmgPpvXv4ixFWZ5ptAYZ6PD28Sq49uo34VyjnmK5H'))
.expect(400)
.expect({
message: 'Error',
errors: [ {
name: 'Error',
message:
'This command does not support the use of a tag. Use an address without a tag.',
code: 1000
} ]
})
.end(done);
});
it('GET settings - fails if RippleAPI returns an invalid result', (done) => {
sinon.stub(rippleApi, 'isConnected').returns(true);
const invalidGetSettingsResponse = {
foo: 'bar'
};
sinon.stub(rippleApi, 'request').resolves(invalidGetSettingsResponse);
request(mockApp)
.get(path.replace('{address}', 'XV5sbjUmgPpvXv4ixFWZ5ptAYZ6PD2gYsjNFQLKYW33DzBm'))
.expect(400)
.expect('{"message":"TypeError","errors":[{"name":"TypeError","message":"Cannot read property \'Flags\' of undefined","code":1000}]}')
.end(done);
});
});