1
|
|
|
import { EventSourcePolyfill as EventSource } from 'event-source-polyfill'; |
2
|
|
|
import { bindToMercureTopic } from '../../../src/mercure/helpers'; |
3
|
|
|
|
4
|
|
|
jest.mock('event-source-polyfill'); |
|
|
|
|
5
|
|
|
|
6
|
|
|
describe('helpers', () => { |
7
|
|
|
afterEach(jest.resetAllMocks); |
|
|
|
|
8
|
|
|
|
9
|
|
|
describe('bindToMercureTopic', () => { |
10
|
|
|
const onMessage = jest.fn(); |
|
|
|
|
11
|
|
|
const onTokenExpired = jest.fn(); |
12
|
|
|
|
13
|
|
|
it.each([ |
|
|
|
|
14
|
|
|
[{ loading: true, error: false }], |
15
|
|
|
[{ loading: false, error: true }], |
16
|
|
|
[{ loading: true, error: true }], |
17
|
|
|
])('does not bind an EventSource when loading or error', (mercureInfo) => { |
18
|
|
|
bindToMercureTopic(mercureInfo)(); |
19
|
|
|
|
20
|
|
|
expect(EventSource).not.toHaveBeenCalled(); |
|
|
|
|
21
|
|
|
expect(onMessage).not.toHaveBeenCalled(); |
22
|
|
|
expect(onTokenExpired).not.toHaveBeenCalled(); |
23
|
|
|
}); |
24
|
|
|
|
25
|
|
|
it('binds an EventSource when mercure info is properly loaded', () => { |
26
|
|
|
const token = 'abc.123.efg'; |
27
|
|
|
const mercureHubUrl = 'https://example.com/.well-known/mercure'; |
28
|
|
|
const topic = 'foo'; |
29
|
|
|
const hubUrl = new URL(mercureHubUrl); |
|
|
|
|
30
|
|
|
|
31
|
|
|
hubUrl.searchParams.append('topic', topic); |
32
|
|
|
|
33
|
|
|
const callback = bindToMercureTopic({ |
34
|
|
|
loading: false, |
35
|
|
|
error: false, |
36
|
|
|
mercureHubUrl, |
37
|
|
|
token, |
38
|
|
|
}, topic, onMessage, onTokenExpired)(); |
39
|
|
|
|
40
|
|
|
expect(EventSource).toHaveBeenCalledWith(hubUrl, { |
|
|
|
|
41
|
|
|
headers: { |
42
|
|
|
Authorization: `Bearer ${token}`, |
43
|
|
|
}, |
44
|
|
|
}); |
45
|
|
|
|
46
|
|
|
const [ es ] = EventSource.mock.instances; |
47
|
|
|
|
48
|
|
|
es.onmessage({ data: '{"foo": "bar"}' }); |
49
|
|
|
es.onerror({ status: 401 }); |
50
|
|
|
expect(onMessage).toHaveBeenCalledWith({ foo: 'bar' }); |
51
|
|
|
expect(onTokenExpired).toHaveBeenCalled(); |
52
|
|
|
|
53
|
|
|
callback(); |
54
|
|
|
expect(es.close).toHaveBeenCalled(); |
55
|
|
|
}); |
56
|
|
|
}); |
57
|
|
|
}); |
58
|
|
|
|
This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.
To learn more about declaring variables in Javascript, see the MDN.