2020-04-18 13:49:03 +03:00
|
|
|
import { EventSourcePolyfill as EventSource } from 'event-source-polyfill';
|
2020-08-29 14:51:53 +03:00
|
|
|
import { Mock } from 'ts-mockery';
|
|
|
|
import { identity } from 'ramda';
|
2020-04-18 13:49:03 +03:00
|
|
|
import { bindToMercureTopic } from '../../../src/mercure/helpers';
|
2020-08-29 14:51:53 +03:00
|
|
|
import { MercureInfo } from '../../../src/mercure/reducers/mercureInfo';
|
2020-04-18 13:49:03 +03:00
|
|
|
|
|
|
|
jest.mock('event-source-polyfill');
|
|
|
|
|
|
|
|
describe('helpers', () => {
|
|
|
|
afterEach(jest.resetAllMocks);
|
|
|
|
|
|
|
|
describe('bindToMercureTopic', () => {
|
|
|
|
const onMessage = jest.fn();
|
|
|
|
const onTokenExpired = jest.fn();
|
|
|
|
|
|
|
|
it.each([
|
2020-08-29 14:51:53 +03:00
|
|
|
[ Mock.of<MercureInfo>({ loading: true, error: false, mercureHubUrl: 'foo' }) ],
|
|
|
|
[ Mock.of<MercureInfo>({ loading: false, error: true, mercureHubUrl: 'foo' }) ],
|
|
|
|
[ Mock.of<MercureInfo>({ loading: true, error: true, mercureHubUrl: 'foo' }) ],
|
|
|
|
[ Mock.of<MercureInfo>({ loading: false, error: false, mercureHubUrl: undefined }) ],
|
|
|
|
[ Mock.of<MercureInfo>({ loading: true, error: true, mercureHubUrl: undefined }) ],
|
|
|
|
])('does not bind an EventSource when loading, error or no hub URL', (mercureInfo) => {
|
2020-09-12 09:52:03 +03:00
|
|
|
bindToMercureTopic(mercureInfo, '', identity, identity);
|
2020-04-18 13:49:03 +03:00
|
|
|
|
|
|
|
expect(EventSource).not.toHaveBeenCalled();
|
|
|
|
expect(onMessage).not.toHaveBeenCalled();
|
|
|
|
expect(onTokenExpired).not.toHaveBeenCalled();
|
|
|
|
});
|
|
|
|
|
|
|
|
it('binds an EventSource when mercure info is properly loaded', () => {
|
|
|
|
const token = 'abc.123.efg';
|
|
|
|
const mercureHubUrl = 'https://example.com/.well-known/mercure';
|
|
|
|
const topic = 'foo';
|
|
|
|
const hubUrl = new URL(mercureHubUrl);
|
|
|
|
|
|
|
|
hubUrl.searchParams.append('topic', topic);
|
|
|
|
|
|
|
|
const callback = bindToMercureTopic({
|
|
|
|
loading: false,
|
|
|
|
error: false,
|
|
|
|
mercureHubUrl,
|
|
|
|
token,
|
2020-09-12 09:52:03 +03:00
|
|
|
}, topic, onMessage, onTokenExpired);
|
2020-04-18 13:49:03 +03:00
|
|
|
|
|
|
|
expect(EventSource).toHaveBeenCalledWith(hubUrl, {
|
|
|
|
headers: {
|
|
|
|
Authorization: `Bearer ${token}`,
|
|
|
|
},
|
|
|
|
});
|
|
|
|
|
|
|
|
const [ es ] = EventSource.mock.instances;
|
|
|
|
|
|
|
|
es.onmessage({ data: '{"foo": "bar"}' });
|
|
|
|
es.onerror({ status: 401 });
|
|
|
|
expect(onMessage).toHaveBeenCalledWith({ foo: 'bar' });
|
|
|
|
expect(onTokenExpired).toHaveBeenCalled();
|
|
|
|
|
2020-08-29 14:51:53 +03:00
|
|
|
callback?.();
|
2020-04-18 13:49:03 +03:00
|
|
|
expect(es.close).toHaveBeenCalled();
|
|
|
|
});
|
|
|
|
});
|
|
|
|
});
|