1
|
|
|
import { EventSourcePolyfill as EventSource } from 'event-source-polyfill'; |
2
|
|
|
import { Mock } from 'ts-mockery'; |
3
|
|
|
import { identity } from 'ramda'; |
4
|
|
|
import { bindToMercureTopic } from '../../../src/mercure/helpers'; |
5
|
|
|
import { MercureInfo } from '../../../src/mercure/reducers/mercureInfo'; |
6
|
|
|
|
7
|
|
|
jest.mock('event-source-polyfill'); |
8
|
|
|
|
9
|
|
|
describe('helpers', () => { |
10
|
|
|
afterEach(jest.resetAllMocks); |
11
|
|
|
|
12
|
|
|
describe('bindToMercureTopic', () => { |
13
|
|
|
const onMessage = jest.fn(); |
14
|
|
|
const onTokenExpired = jest.fn(); |
15
|
|
|
|
16
|
|
|
it.each([ |
17
|
|
|
[ Mock.of<MercureInfo>({ loading: true, error: false, mercureHubUrl: 'foo' }) ], |
18
|
|
|
[ Mock.of<MercureInfo>({ loading: false, error: true, mercureHubUrl: 'foo' }) ], |
19
|
|
|
[ Mock.of<MercureInfo>({ loading: true, error: true, mercureHubUrl: 'foo' }) ], |
20
|
|
|
[ Mock.of<MercureInfo>({ loading: false, error: false, mercureHubUrl: undefined }) ], |
21
|
|
|
[ Mock.of<MercureInfo>({ loading: true, error: true, mercureHubUrl: undefined }) ], |
22
|
|
|
])('does not bind an EventSource when loading, error or no hub URL', (mercureInfo) => { |
23
|
|
|
bindToMercureTopic(mercureInfo, '', identity, identity); |
24
|
|
|
|
25
|
|
|
expect(EventSource).not.toHaveBeenCalled(); |
26
|
|
|
expect(onMessage).not.toHaveBeenCalled(); |
27
|
|
|
expect(onTokenExpired).not.toHaveBeenCalled(); |
28
|
|
|
}); |
29
|
|
|
|
30
|
|
|
it('binds an EventSource when mercure info is properly loaded', () => { |
31
|
|
|
const token = 'abc.123.efg'; |
32
|
|
|
const mercureHubUrl = 'https://example.com/.well-known/mercure'; |
33
|
|
|
const topic = 'foo'; |
34
|
|
|
const hubUrl = new URL(mercureHubUrl); |
35
|
|
|
|
36
|
|
|
hubUrl.searchParams.append('topic', topic); |
37
|
|
|
|
38
|
|
|
const callback = bindToMercureTopic({ |
39
|
|
|
loading: false, |
40
|
|
|
error: false, |
41
|
|
|
mercureHubUrl, |
42
|
|
|
token, |
43
|
|
|
}, topic, onMessage, onTokenExpired); |
44
|
|
|
|
45
|
|
|
expect(EventSource).toHaveBeenCalledWith(hubUrl, { |
46
|
|
|
headers: { |
47
|
|
|
Authorization: `Bearer ${token}`, |
48
|
|
|
}, |
49
|
|
|
}); |
50
|
|
|
|
51
|
|
|
const [ es ] = EventSource.mock.instances; |
52
|
|
|
|
53
|
|
|
es.onmessage({ data: '{"foo": "bar"}' }); |
54
|
|
|
es.onerror({ status: 401 }); |
55
|
|
|
expect(onMessage).toHaveBeenCalledWith({ foo: 'bar' }); |
56
|
|
|
expect(onTokenExpired).toHaveBeenCalled(); |
57
|
|
|
|
58
|
|
|
callback?.(); |
59
|
|
|
expect(es.close).toHaveBeenCalled(); |
60
|
|
|
}); |
61
|
|
|
}); |
62
|
|
|
}); |
63
|
|
|
|