xref: /aosp_15_r20/external/perfetto/ui/src/base/events_unittest.ts (revision 6dbdd20afdafa5e3ca9b8809fa73465d530080dc)
1// Copyright (C) 2023 The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//      http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15import {defer} from './deferred';
16import {DisposableStack} from './disposable_stack';
17import {EvtSource} from './events';
18
19describe('Events', () => {
20  test('voidEvent', () => {
21    const ev = new EvtSource<void>();
22    const calls: string[] = [];
23    ev.addListener(() => calls.push('listener1'));
24    ev.addListener(() => calls.push('listener2'));
25    ev.notify();
26    expect(calls).toEqual(['listener1', 'listener2']);
27    ev.notify();
28    expect(calls).toEqual(['listener1', 'listener2', 'listener1', 'listener2']);
29  });
30
31  test('eventWithArgs', () => {
32    const ev = new EvtSource<number>();
33    const argsReceived = new Array<number>();
34    ev.addListener((n: number) => argsReceived.push(n));
35    ev.notify(1);
36    ev.notify(2);
37    expect(argsReceived).toEqual([1, 2]);
38  });
39
40  test('asyncEvent', async () => {
41    const ev = new EvtSource<number>();
42    const argsReceived = new Array<number>();
43    ev.addListener((n: number) => {
44      const promise = defer<void>();
45      setTimeout(() => {
46        argsReceived.push(n);
47        promise.resolve();
48      }, 0);
49      return promise;
50    });
51    await ev.notify(1);
52    await ev.notify(2);
53    await ev.notify(3);
54    expect(argsReceived).toEqual([1, 2, 3]);
55  });
56
57  test('dispose', () => {
58    const ev = new EvtSource<void>();
59    const calls: string[] = [];
60    const trash = new DisposableStack();
61    trash.use(ev.addListener(() => calls.push('listener1')));
62    trash.use(ev.addListener(() => calls.push('listener2')));
63    ev.notify();
64    expect(calls).toEqual(['listener1', 'listener2']);
65    calls.splice(0);
66
67    trash.dispose();
68    ev.notify();
69    expect(calls).toEqual([]);
70
71    trash.use(ev.addListener(() => calls.push('listener3')));
72    ev.notify();
73    expect(calls).toEqual(['listener3']);
74  });
75});
76