Skip to content
This repository was archived by the owner on Feb 4, 2022. It is now read-only.

Commit fa276fa

Browse files
committed
Add simple client test
1 parent 7d345b8 commit fa276fa

File tree

3 files changed

+68
-0
lines changed

3 files changed

+68
-0
lines changed

pubspec.yaml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ dependencies:
2828
collection: ^1.14.11
2929

3030
dev_dependencies:
31+
async: ^2.8.2
3132
build_runner: ^2.0.3
3233
build_test: ^2.1.0
3334
web_socket_channel: ^2.0.0

test/core/client_test.dart

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import 'package:test/test.dart';
2+
import 'package:web3dart/web3dart.dart';
3+
4+
import '../mock_client.dart';
5+
6+
void main() {
7+
test('getClientVersion', () async {
8+
final client = MockClient(expectAsync2((method, data) {
9+
expect(method, 'web3_clientVersion');
10+
return 'dart-web3dart-test';
11+
}));
12+
final web3 = Web3Client('', client);
13+
addTearDown(web3.dispose);
14+
15+
expect(web3.getClientVersion(), completion('dart-web3dart-test'));
16+
});
17+
}

test/mock_client.dart

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
import 'dart:convert';
2+
3+
import 'package:async/async.dart';
4+
import 'package:http/http.dart';
5+
import 'package:test/test.dart';
6+
7+
class MockClient extends BaseClient {
8+
static final _jsonUtf8 = json.fuse(utf8);
9+
10+
final Object? Function(String method, Object? payload) handler;
11+
12+
MockClient(this.handler);
13+
14+
@override
15+
Future<StreamedResponse> send(BaseRequest request) async {
16+
final data = await _jsonUtf8.decoder.bind(request.finalize()).first;
17+
18+
if (data is! Map) {
19+
fail('Invalid request, expected JSON map');
20+
}
21+
22+
if (data['jsonrpc'] != '2.0') {
23+
fail('Expected request to contain correct jsonrpc key');
24+
}
25+
26+
final id = data['id'];
27+
final method = data['method'] as String;
28+
final params = data['params'];
29+
30+
final response = Result(() => handler(method, params));
31+
32+
return StreamedResponse(
33+
_jsonUtf8.encoder.bind(
34+
Stream.value(
35+
{
36+
'jsonrpc': '2.0',
37+
if (response is ValueResult) 'result': response.value,
38+
if (response is ErrorResult)
39+
'error': {
40+
'code': -1,
41+
'message': '${response.error}',
42+
},
43+
'id': id,
44+
},
45+
),
46+
),
47+
200,
48+
);
49+
}
50+
}

0 commit comments

Comments
 (0)