-
Notifications
You must be signed in to change notification settings - Fork 230
Expand file tree
/
Copy pathlayout.ts
More file actions
286 lines (253 loc) · 8.86 KB
/
layout.ts
File metadata and controls
286 lines (253 loc) · 8.86 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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import { Page, expect } from '@playwright/test';
import { BaseTarget } from '../lib/targets/base';
import {
FirefoxCommandResponse,
FirefoxCommandRequest,
FirefoxCommand,
} from '../lib/channels';
export abstract class BaseLayout {
/**
* The expected path of the current page. This works with checkPath(). If left empty,
* checkPath will always pass. If defined, checkPass will enforce that this value is
* in the URL.
*/
abstract get path(): string;
constructor(
public page: Page,
protected readonly target: BaseTarget
) {}
protected get baseUrl() {
return this.target.baseUrl;
}
get url() {
return `${this.baseUrl}/${this.path}`;
}
/**
* Checks that the current path maps to the POM's expected path. This can be called before querying for locators in
* child classes to make locators more robust and avoid false positives. If the current path does not exist in the URL,
* an error will be thrown.
*/
checkPath() {
if (this.path) {
if (this.page.url().indexOf(this.path) < 0) {
throw new Error(
`Invalid page state detected! Expected ${
this.path
} to be in url, ${this.page.url()}`
);
}
}
}
goto(
waitUntil: 'networkidle' | 'domcontentloaded' | 'load' = 'load',
query?: string | URLSearchParams
) {
const url = query ? `${this.url}?${query}` : this.url;
return this.page.goto(url, { waitUntil });
}
screenshot() {
return this.page.screenshot({ fullPage: true });
}
async clearCache() {
await this.page.goto(`${this.target.contentServerUrl}/clear`);
await this.page.context().clearCookies();
await this.page.waitForTimeout(2000);
}
async clearSessionStorage() {
await this.page.evaluate(() => {
sessionStorage.clear();
});
}
async checkWebChannelMessage(command: FirefoxCommand) {
// Retry across navigations — a client-side redirect after page.goto
// can destroy the execution context mid-evaluate.
await expect(async () => {
const messages = await this.page.evaluate(() =>
JSON.parse(sessionStorage.getItem('webChannelEvents') || '[]')
);
const found = messages.find(
(x: { command: string }) => x.command === command
);
expect(found).toBeTruthy();
}).toPass({ timeout: 5000 });
}
async getWebChannelEvents(): Promise<
Array<{ command: string; data: Record<string, unknown> }>
> {
return await this.page.evaluate(() => {
return JSON.parse(sessionStorage.getItem('webChannelEvents') || '[]');
});
}
async clearWebChannelEvents() {
await this.page.evaluate(() => {
sessionStorage.removeItem('webChannelEvents');
});
}
/**
* Asserts that a web channel message with the given command was sent
* and contains the expected services object in its data.
*/
async checkWebChannelMessageServices(
command: FirefoxCommand,
expectedServices: Record<string, unknown>
) {
await this.checkWebChannelMessage(command);
const events = await this.getWebChannelEvents();
const event = events.find((e) => e.command === command);
if (!event) {
throw new Error(`No web channel event found for command: ${command}`);
}
const services = (event.data as { services?: unknown })?.services;
if (JSON.stringify(services) !== JSON.stringify(expectedServices)) {
throw new Error(
`Expected services ${JSON.stringify(expectedServices)} but got ${JSON.stringify(services)}`
);
}
}
/**
* Asserts that a web channel message with the given command was sent
* and contains the expected scope string in its data.
*/
async checkWebChannelMessageScopes(
command: FirefoxCommand,
expectedScope: string
) {
await this.checkWebChannelMessage(command);
const events = await this.getWebChannelEvents();
const event = events.find((e) => e.command === command);
if (!event) {
throw new Error(`No web channel event found for command: ${command}`);
}
const scopes = (event.data as { scopes?: string })?.scopes;
if (!scopes?.includes(expectedScope)) {
throw new Error(
`Expected scopes to contain "${expectedScope}" but got "${scopes}"`
);
}
}
async listenToWebChannelMessages() {
await this.page.evaluate(() => {
function listener(msg: { detail: string }) {
const detail = JSON.parse(msg.detail);
const events = JSON.parse(
sessionStorage.getItem('webChannelEvents') || '[]'
);
events.push({
command: detail.message.command,
data: detail.message.data,
});
sessionStorage.setItem('webChannelEvents', JSON.stringify(events));
}
// @ts-ignore
addEventListener('WebChannelMessageToChrome', listener);
});
}
/**
* Send a web channel message from browser to web content.
* NOTE: Prefer `respondToWebChannelMessage` where possible! This should only be
* used when we can't attach a listener in time (which respondToWebChannelMessage
* does) because the event is fired on page load before the listener can attach.
* This currently happens on React SignUp and SignIn which we should revisit when the index
* index page has been converted to React and our event handling moved.
*/
async sendWebChannelMessage(customEventDetail: FirefoxCommandRequest) {
// Using waitForTimeout is naturally flaky, I'm not sure of other options
// to ensure that browser has had time send all web channel messages.
await this.page.waitForTimeout(2000);
await this.page.evaluate(
({ customEventDetail }) => {
window.dispatchEvent(
new CustomEvent('WebChannelMessageToContent', {
detail: customEventDetail,
})
);
},
{ customEventDetail }
);
}
/**
* Listens for a `WebChannelMessageToChrome` web channel event which
* occurs when we (web content) send a message to the browser.
*
* Responds with a `WebChannelMessageToContent` event containing event
* details passed in only when the given command matches the command from
* the listened-for event.
*
* @param webChannelMessage - Custom event details to send to the web content.
*/
async respondToWebChannelMessage(webChannelMessage: FirefoxCommandResponse) {
const expectedCommand = webChannelMessage.message.command;
const response = webChannelMessage.message.data;
await this.page.addInitScript(
({ expectedCommand, response }) => {
function listener(e: CustomEvent) {
const detail = JSON.parse(e.detail);
const command = detail.message.command;
const messageId = detail.message.messageId;
if (command === expectedCommand) {
// @ts-ignore
window.removeEventListener('WebChannelMessageToChrome', listener);
const event = new CustomEvent('WebChannelMessageToContent', {
detail: {
id: 'account_updates',
message: {
command,
data: response,
messageId,
},
},
});
window.dispatchEvent(event);
}
}
function startListening() {
try {
// @ts-ignore
window.addEventListener('WebChannelMessageToChrome', listener);
} catch (e) {
// problem adding the listener, window may not be
// ready, try again.
setTimeout(startListening, 0);
}
}
startListening();
},
{ expectedCommand, response }
);
}
async getAccountFromLocalStorage(email: string) {
return await this.page.evaluate((email) => {
const accounts: Array<{
email: string;
sessionToken: string;
uid: string;
}> = JSON.parse(localStorage.getItem('__fxa_storage.accounts') || '{}');
return Object.values(accounts).find((x) => x.email === email);
}, email);
}
async destroySession(email: string) {
const account = await this.getAccountFromLocalStorage(email);
if (account?.sessionToken) {
return await this.target.authClient.sessionDestroy(account.sessionToken);
}
}
async denormalizeStoredEmail(email: string) {
return this.page.evaluate((uid) => {
const accounts = JSON.parse(
localStorage.getItem('__fxa_storage.accounts') || '{}'
);
for (const accountId in accounts) {
if (accountId === uid) {
const account = accounts[accountId];
if (account.email === email) {
account.email = email.toUpperCase();
}
}
}
localStorage.setItem('__fxa_storage.accounts', JSON.stringify(accounts));
}, email);
}
}