• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/*
2 * Copyright (C) 2023 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17import {ComponentFixture, flush} from '@angular/core/testing';
18
19export function dispatchMouseEvent(
20  source: Node,
21  type: string,
22  screenX: number,
23  screenY: number,
24  clientX: number,
25  clientY: number,
26) {
27  const event = document.createEvent('MouseEvent');
28
29  event.initMouseEvent(
30    type,
31    true /* canBubble */,
32    false /* cancelable */,
33    window /* view */,
34    0 /* detail */,
35    screenX /* screenX */,
36    screenY /* screenY */,
37    clientX /* clientX */,
38    clientY /* clientY */,
39    false /* ctrlKey */,
40    false /* altKey */,
41    false /* shiftKey */,
42    false /* metaKey */,
43    0 /* button */,
44    null /* relatedTarget */,
45  );
46  Object.defineProperty(event, 'buttons', {get: () => 1});
47
48  source.dispatchEvent(event);
49}
50
51export function dragElement<T>(
52  fixture: ComponentFixture<T>,
53  target: Element,
54  x: number,
55  y: number,
56) {
57  const {left, top} = target.getBoundingClientRect();
58
59  dispatchMouseEvent(target, 'mousedown', left, top, 0, 0);
60  fixture.detectChanges();
61  flush();
62  dispatchMouseEvent(document, 'mousemove', left + 1, top + 0, 1, y);
63  fixture.detectChanges();
64  flush();
65  dispatchMouseEvent(document, 'mousemove', left + x, top + y, x, y);
66  fixture.detectChanges();
67  flush();
68  dispatchMouseEvent(document, 'mouseup', left + x, top + y, x, y);
69  fixture.detectChanges();
70
71  flush();
72}
73
74export async function waitToBeCalled(
75  spy: jasmine.Spy,
76  times: number = 1,
77  timeout = 10000,
78) {
79  return new Promise<void>((resolve, reject) => {
80    let called = 0;
81    spy.and.callThrough().and.callFake(() => {
82      called++;
83      if (called === times) {
84        resolve();
85      }
86    });
87
88    setTimeout(
89      () => reject(`not called ${times} times within ${timeout}ms`),
90      timeout,
91    );
92  });
93}
94