1 |
|
2 |
|
3 |
|
4 |
|
5 | import { mockWs, TEST_WS_URL } from '../../test/mockWs';
|
6 |
|
7 | import Ws from './index';
|
8 |
|
9 | let ws;
|
10 | let mock;
|
11 |
|
12 | function createMock (requests) {
|
13 | mock = mockWs(requests);
|
14 | }
|
15 |
|
16 | function createWs (autoConnect) {
|
17 | ws = new Ws(TEST_WS_URL, autoConnect);
|
18 |
|
19 | return ws;
|
20 | }
|
21 |
|
22 | describe('send', () => {
|
23 | let globalWs;
|
24 |
|
25 | beforeEach(() => {
|
26 | globalWs = global.WebSocket;
|
27 | });
|
28 |
|
29 | afterEach(() => {
|
30 | global.WebSocket = globalWs;
|
31 |
|
32 | if (mock) {
|
33 | mock.done();
|
34 | mock = null;
|
35 | }
|
36 | });
|
37 |
|
38 | it('handles internal errors', () => {
|
39 | createMock([]);
|
40 |
|
41 | let websocket;
|
42 |
|
43 | global.WebSocket = class {
|
44 | constructor () {
|
45 | websocket = this;
|
46 | }
|
47 |
|
48 | send () {
|
49 | throw new Error('send error');
|
50 | }
|
51 | };
|
52 |
|
53 | ws = createWs();
|
54 | websocket.onopen();
|
55 |
|
56 | return ws
|
57 | .send('test_encoding', ['param'])
|
58 | .catch((error) => {
|
59 | expect(error.message).toEqual('send error');
|
60 | });
|
61 | });
|
62 |
|
63 | it('passes the body through correctly', () => {
|
64 | createMock([{
|
65 | id: 1,
|
66 | method: 'test_body',
|
67 | reply: {
|
68 | result: 'ok'
|
69 | }
|
70 | }]);
|
71 |
|
72 | return createWs()
|
73 | .send('test_body', ['param'])
|
74 | .then((result) => {
|
75 | expect(
|
76 | mock.body['test_body']
|
77 | ).toEqual('{"id":1,"jsonrpc":"2.0","method":"test_body","params":["param"]}');
|
78 | });
|
79 | });
|
80 |
|
81 | it('throws error when !response.ok', () => {
|
82 | createMock([{
|
83 | id: 1,
|
84 | error: {
|
85 | code: 666,
|
86 | message: 'error'
|
87 | }
|
88 | }]);
|
89 |
|
90 | return createWs()
|
91 | .send('test_error', [])
|
92 | .catch((error) => {
|
93 | expect(error.message).toMatch(/\[666\]: error/);
|
94 | });
|
95 | });
|
96 |
|
97 | it('adds subscriptions', () => {
|
98 | createMock([{
|
99 | id: 1,
|
100 | method: 'test_sub',
|
101 | reply: {
|
102 | result: 1
|
103 | }
|
104 | }]);
|
105 |
|
106 | return createWs()
|
107 | .send('test_sub', [], () => {})
|
108 | .then((id) => {
|
109 | expect(id).toEqual(1);
|
110 | });
|
111 | });
|
112 | });
|