-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwaitForNewTab.ts
More file actions
71 lines (54 loc) · 2.2 KB
/
waitForNewTab.ts
File metadata and controls
71 lines (54 loc) · 2.2 KB
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import {ADDITIONAL_STEP_TIMEOUT, LogEventType} from '../../constants/internal';
import {getTestRunPromise} from '../../context/testRunPromise';
import {step} from '../../step';
import {getPlaywrightPage} from '../../useContext';
import {assertValueIsDefined} from '../../utils/asserts';
import {getFullPackConfig} from '../../utils/config';
import {setCustomInspectOnFunction} from '../../utils/fn';
import {getDurationWithUnits} from '../../utils/getDurationWithUnits';
import type {Page} from '@playwright/test';
import type {InternalTab, Tab, Trigger} from '../../types/internal';
type Options = Readonly<{
skipLogs?: boolean;
timeout?: number;
}>;
type WaitForNewTab = ((trigger: Trigger | undefined, options?: Options) => Promise<Tab>) &
((options?: Options) => Promise<Tab>);
/**
* Waits for opening of new tab and returns this tab.
*/
export const waitForNewTab = (async (
triggerOrOptions?: Options | Trigger | undefined,
options?: Options,
): Promise<Tab> => {
const trigger = typeof triggerOrOptions === 'function' ? triggerOrOptions : undefined;
const finalOptions =
typeof triggerOrOptions === 'function' ? options : (triggerOrOptions ?? options);
const timeout = finalOptions?.timeout ?? getFullPackConfig().navigationTimeout;
const timeoutWithUnits = getDurationWithUnits(timeout);
if (trigger !== undefined) {
setCustomInspectOnFunction(trigger);
}
let newTab: InternalTab | undefined;
await step(
`Wait for new tab with timeout ${timeoutWithUnits}`,
async () => {
const context = getPlaywrightPage().context();
const pagePromise = context.waitForEvent('page', {timeout});
await trigger?.();
const testRunPromise = getTestRunPromise();
const page = await Promise.race([pagePromise, testRunPromise]);
newTab = {page: page ?? ({} as unknown as Page)};
const url = page?.url();
return {url};
},
{
payload: {timeoutWithUnits, trigger},
skipLogs: finalOptions?.skipLogs ?? false,
timeout: timeout + ADDITIONAL_STEP_TIMEOUT,
type: LogEventType.InternalCore,
},
);
assertValueIsDefined(newTab, 'newTab is defined', {trigger});
return newTab satisfies InternalTab as Tab;
}) as WaitForNewTab;