summaryrefslogtreecommitdiff
path: root/spec/frontend/lib/utils/pubsub_spec.js
blob: 244e6d3bbc834d540e2df5dee6ddfc1e491a6e37 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import { publish, subscribe } from '~/lib/utils/pubsub';

describe('Pub/sub messaging', () => {
  it('sends and receives messages asynchronously', done => {
    const receiver1 = jest.fn();
    const receiver2 = jest.fn();
    const receiver3 = jest.fn();
    subscribe('namespace:topic', receiver1);
    subscribe('namespace:topic', receiver2);
    subscribe('namespace:topic2', receiver3);

    publish('shoudnotreceive', 'shouldnotreceive');
    publish('namespace:topic', 1);
    publish('namespace:topic', 2);
    publish('namespace:topic2', 3);

    // Receivers should not be called synchronously
    expect(receiver1).not.toHaveBeenCalled();
    expect(receiver2).not.toHaveBeenCalled();
    expect(receiver3).not.toHaveBeenCalled();

    setImmediate(() => {
      expect(receiver1.mock.calls).toEqual([[1], [2]]);
      expect(receiver2.mock.calls).toEqual([[1], [2]]);
      expect(receiver3.mock.calls).toEqual([[3]]);
      done();
    });
  });

  it('allows clients to unsubscribe', done => {
    const receiver = jest.fn();
    const unsubscribe = subscribe('topic', receiver);
    publish('topic', 1);
    unsubscribe();
    publish('topic', 2);
    setImmediate(() => {
      expect(receiver.mock.calls).toEqual([[1]]);
      done();
    });
  });
});