Repository navigation
Expand file tree
/
Copy pathmethod-generation.ts
More file actions
502 lines (464 loc) · 17 KB
/
Copy pathmethod-generation.ts
File metadata and controls
502 lines (464 loc) · 17 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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
// Method content generation helpers.
//
// These are shared between transform-time codegen (building dependencies.methodsContent)
// and class-generation tests. This module is intentionally dependency-free with respect to
// generator internals to avoid circular imports between `utils` and `class-generation`.
import {
createClassGetter,
createClassMethod,
renderClassMembers,
type OptionalKind,
type ParameterDeclarationStructure,
type TypeScriptClassMember,
type WriterFunction,
} from "./typescript-codegen";
import {
getPomParameter,
getPomParameterNames,
toTypeScriptPomParameterStructures,
type PomParameterSpec,
} from "./pom-params";
import {
getIndexedPomPatternVariable,
hasPomPatternVariables,
orderPomPatternParameters,
toTypeScriptPomPatternExpression,
uniquePomStringPatterns,
type PomStringPattern,
} from "./pom-patterns";
import { buildPomLocatorDescription } from "./pom-discoverability";
function upperFirst(value: string): string {
if (!value) {
return value;
}
return value.charAt(0).toUpperCase() + value.slice(1);
}
function generatedActionMetadata(
componentName: string | undefined,
methodName: string,
options: { preferAssociatedLabel?: boolean } = {},
): string {
const preferAssociatedLabel = options.preferAssociatedLabel ? ", preferAssociatedLabel: true" : "";
return `{ componentName: ${JSON.stringify(componentName)}, methodName: ${JSON.stringify(methodName)}${preferAssociatedLabel} }`;
}
function createParameters(params: readonly PomParameterSpec[]): OptionalKind<ParameterDeclarationStructure>[] {
return toTypeScriptPomParameterStructures(params);
}
function createInlineParameter(
name: string,
options: {
type?: string;
initializer?: string;
} = {},
): OptionalKind<ParameterDeclarationStructure> {
return {
name,
type: options.type,
initializer: options.initializer,
};
}
function removeByKeySegment(value: string): string {
const idx = value.lastIndexOf("ByKey");
if (idx < 0) {
return value;
}
return value.slice(0, idx) + value.slice(idx + "ByKey".length);
}
function createAsyncMethod(
name: string,
parameters: OptionalKind<ParameterDeclarationStructure>[],
statements: WriterFunction,
): TypeScriptClassMember {
return createClassMethod({
name,
isAsync: true,
parameters,
statements,
});
}
function generateClickMethod(
componentName: string | undefined,
methodName: string,
nativeRole: string,
selector: PomStringPattern,
alternateSelectors: PomStringPattern[] | undefined,
parameters: PomParameterSpec[],
): TypeScriptClassMember[] {
const name = `click${methodName}`;
const noWaitName = `${name}NoWait`;
const locatorDescription = JSON.stringify(buildPomLocatorDescription({
componentName,
methodName,
nativeRole: "button",
}));
const selectorParams = orderPomPatternParameters(parameters, [selector]);
const hasSelectorVariables = hasPomPatternVariables(selector);
const baseParameters = createParameters(selectorParams);
const argsForForward = getPomParameterNames(selectorParams).join(", ");
const alternates = uniquePomStringPatterns(selector, alternateSelectors).slice(1);
const primaryTestIdExpr = toTypeScriptPomPatternExpression(selector);
const actionMetadata = generatedActionMetadata(componentName, name, {
preferAssociatedLabel: nativeRole === "checkbox",
});
if (alternates.length > 0) {
const candidatesExpr = [primaryTestIdExpr, ...alternates.map(id => toTypeScriptPomPatternExpression(id))].join(", ");
const clickMethod = createAsyncMethod(
name,
hasSelectorVariables
? [
...baseParameters,
createInlineParameter("wait", { type: "boolean", initializer: "true" }),
createInlineParameter("annotationText", { type: "string", initializer: "\"\"" }),
]
: [
createInlineParameter("wait", { type: "boolean", initializer: "true" }),
createInlineParameter("annotationText", { type: "string", initializer: "\"\"" }),
],
(writer) => {
writer.writeLine(`const candidates = [${candidatesExpr}] as const;`);
writer.writeLine(`const locator = await this.resolveVisibleTestIdLocator(candidates, ${locatorDescription}, ${JSON.stringify(name)}, ${JSON.stringify(componentName)});`);
writer.writeLine("await this.clickLocator(locator, annotationText, wait);");
},
);
const noWaitArgs = argsForForward ? `${argsForForward}, false, annotationText` : "false, annotationText";
const noWaitMethod = createAsyncMethod(
noWaitName,
hasSelectorVariables
? [...baseParameters, createInlineParameter("annotationText", { type: "string", initializer: "\"\"" })]
: [createInlineParameter("annotationText", { type: "string", initializer: "\"\"" })],
(writer) => {
writer.writeLine(`await this.${name}(${noWaitArgs});`);
},
);
return [clickMethod, noWaitMethod];
}
if (hasSelectorVariables) {
return [
createAsyncMethod(
name,
[
...baseParameters,
createInlineParameter("wait", { type: "boolean", initializer: "true" }),
createInlineParameter("annotationText", { type: "string", initializer: "\"\"" }),
],
(writer) => {
writer.writeLine(`await this.clickByTestId(${primaryTestIdExpr}, annotationText, wait, ${locatorDescription}, ${actionMetadata});`);
},
),
createAsyncMethod(
noWaitName,
[...baseParameters, createInlineParameter("annotationText", { type: "string", initializer: "\"\"" })],
(writer) => {
writer.writeLine(`await this.${name}(${argsForForward}, false, annotationText);`);
},
),
];
}
return [
createAsyncMethod(
name,
[
createInlineParameter("wait", { type: "boolean", initializer: "true" }),
createInlineParameter("annotationText", { type: "string", initializer: "\"\"" }),
],
(writer) => {
writer.writeLine(`await this.clickByTestId(${primaryTestIdExpr}, annotationText, wait, ${locatorDescription}, ${actionMetadata});`);
},
),
createAsyncMethod(
noWaitName,
[createInlineParameter("annotationText", { type: "string", initializer: "\"\"" })],
(writer) => {
writer.writeLine(`await this.${name}(false, annotationText);`);
},
),
];
}
function generateRadioMethod(
componentName: string | undefined,
methodName: string,
selector: PomStringPattern,
parameters: PomParameterSpec[],
): TypeScriptClassMember[] {
const name = `select${methodName}`;
const locatorDescription = JSON.stringify(buildPomLocatorDescription({
componentName,
methodName,
nativeRole: "radio",
}));
const selectorParams = orderPomPatternParameters(parameters, [selector]);
const methodParameters = createParameters(selectorParams);
const testIdExpr = toTypeScriptPomPatternExpression(selector);
return [
createAsyncMethod(name, methodParameters, (writer) => {
writer.writeLine(`await this.clickByTestId(${testIdExpr}, annotationText, true, ${locatorDescription}, ${generatedActionMetadata(componentName, name, { preferAssociatedLabel: true })});`);
}),
];
}
function generateSelectMethod(
componentName: string | undefined,
methodName: string,
selector: PomStringPattern,
parameters: PomParameterSpec[],
): TypeScriptClassMember[] {
const name = `select${methodName}`;
const locatorDescription = JSON.stringify(buildPomLocatorDescription({
componentName,
methodName,
nativeRole: "select",
}));
const selectorParams = orderPomPatternParameters(parameters, [selector]);
const testIdExpr = toTypeScriptPomPatternExpression(selector);
return [
createAsyncMethod(
name,
createParameters(selectorParams),
(writer) => {
writer.writeLine(`const testId = ${testIdExpr};`);
writer.writeLine(`this.recordPomAction(${JSON.stringify(componentName)}, ${JSON.stringify(name)}, [testId]);`);
writer.writeLine(`const locator = this.locatorByTestId(testId, ${locatorDescription}).filter({ visible: true }).first();`);
writer.writeLine("await this.animateCursorToElement(locator, false, 500, annotationText);");
writer.writeLine("await locator.selectOption(value);");
},
),
];
}
function generateVSelectMethod(
componentName: string | undefined,
methodName: string,
selector: PomStringPattern,
parameters: PomParameterSpec[],
): TypeScriptClassMember[] {
const name = `select${methodName}`;
const locatorDescription = JSON.stringify(buildPomLocatorDescription({
componentName,
methodName,
nativeRole: "vselect",
}));
const selectorParams = orderPomPatternParameters(parameters, [selector])
.filter(parameter => parameter.name !== "timeOut" && parameter.name !== "timeout");
return [
createAsyncMethod(
name,
createParameters(selectorParams),
(writer) => {
writer.writeLine(`await this.selectVSelectByTestId(${toTypeScriptPomPatternExpression(selector)}, value, annotationText, ${locatorDescription}, ${generatedActionMetadata(componentName, name)});`);
},
),
];
}
function generateTypeMethod(
componentName: string | undefined,
methodName: string,
selector: PomStringPattern,
parameters: PomParameterSpec[],
): TypeScriptClassMember[] {
const name = `type${methodName}`;
const locatorDescription = JSON.stringify(buildPomLocatorDescription({
componentName,
methodName,
nativeRole: "input",
}));
const selectorParams = orderPomPatternParameters(parameters, [selector]);
return [
createAsyncMethod(
name,
createParameters(selectorParams),
(writer) => {
writer.writeLine(`await this.fillInputByTestId(${toTypeScriptPomPatternExpression(selector)}, text, annotationText, ${locatorDescription}, ${generatedActionMetadata(componentName, name)});`);
},
),
];
}
function isAllDigits(value: string): boolean {
if (!value)
return false;
for (let i = 0; i < value.length; i++) {
const code = value.charCodeAt(i);
if (code < 48 || code > 57)
return false;
}
return true;
}
function generateGetElementByDataTestId(
componentName: string | undefined,
methodName: string,
nativeRole: string,
selector: PomStringPattern,
alternateSelectors: PomStringPattern[] | undefined,
getterNameOverride: string | undefined,
parameters: PomParameterSpec[],
): TypeScriptClassMember[] {
const locatorDescription = JSON.stringify(buildPomLocatorDescription({
componentName,
methodName,
nativeRole,
}));
const roleSuffix = upperFirst(nativeRole || "Element");
const baseName = upperFirst(methodName);
const numericSuffix = baseName.startsWith(roleSuffix) ? baseName.slice(roleSuffix.length) : "";
const hasRoleSuffix = baseName.endsWith(roleSuffix) || (baseName.startsWith(roleSuffix) && isAllDigits(numericSuffix));
const propertyName = hasRoleSuffix ? `${baseName}` : `${baseName}${roleSuffix}`;
const selectorParams = orderPomPatternParameters(parameters, [selector]);
const indexedVariable = getIndexedPomPatternVariable(selector);
if (indexedVariable) {
const keyType = getPomParameter(selectorParams, indexedVariable)?.typeExpression || "string";
const keyedPropertyName = getterNameOverride ?? removeByKeySegment(propertyName);
return [
createClassGetter({
name: keyedPropertyName,
statements: [
`return this.keyedLocators((${indexedVariable}: ${keyType}) => this.locatorByTestId(${toTypeScriptPomPatternExpression(selector)}, ${locatorDescription}));`,
],
}),
];
}
const finalPropertyName = getterNameOverride ?? propertyName;
const alternates = uniquePomStringPatterns(selector, alternateSelectors).slice(1);
if (alternates.length > 0) {
const all = [selector, ...alternates];
const locatorExpr = all
.map(id => `this.locatorByTestId(${toTypeScriptPomPatternExpression(id)})`)
.reduce((acc, next) => `${acc}.or(${next})`);
return [
createClassGetter({
name: finalPropertyName,
statements: [`return this.describeLocator(${locatorExpr}, ${locatorDescription});`],
}),
];
}
return [
createClassGetter({
name: finalPropertyName,
statements: [`return this.locatorByTestId(${toTypeScriptPomPatternExpression(selector)}, ${locatorDescription});`],
}),
];
}
function generateNavigationMethod(args: {
componentName?: string;
targetPageObjectModelClass: string;
baseMethodName: string;
selector: PomStringPattern;
alternateSelectors?: PomStringPattern[];
parameters: PomParameterSpec[];
}): TypeScriptClassMember[] {
const { componentName, targetPageObjectModelClass: target, baseMethodName, selector, alternateSelectors, parameters } = args;
const methodName = baseMethodName
? `goTo${upperFirst(baseMethodName)}`
: `goTo${target.endsWith("Page") ? target.slice(0, -"Page".length) : target}`;
const locatorDescription = JSON.stringify(buildPomLocatorDescription({
componentName,
methodName: baseMethodName,
nativeRole: "button",
}));
const selectorParams = orderPomPatternParameters(parameters, [selector]);
const methodParameters = createParameters(selectorParams);
const alternates = uniquePomStringPatterns(selector, alternateSelectors).slice(1);
const candidatesExpr = [toTypeScriptPomPatternExpression(selector), ...alternates.map(id => toTypeScriptPomPatternExpression(id))].join(", ");
if (alternates.length > 0) {
return [
createClassMethod({
name: methodName,
parameters: methodParameters,
returnType: `Fluent<${target}>`,
statements: (writer) => {
writer.write("return this.fluent(async () => ").block(() => {
writer.writeLine(`const candidates = [${candidatesExpr}] as const;`);
writer.writeLine(`const locator = await this.resolveVisibleTestIdLocator(candidates, ${locatorDescription}, ${JSON.stringify(methodName)}, ${JSON.stringify(componentName)});`);
writer.writeLine("await this.clickLocator(locator);");
writer.writeLine(`return new ${target}(this.page);`);
});
writer.writeLine(");");
},
}),
];
}
return [
createClassMethod({
name: methodName,
parameters: methodParameters,
returnType: `Fluent<${target}>`,
statements: (writer) => {
writer.write("return this.fluent(async () => ").block(() => {
writer.writeLine(`const locator = this.locatorByTestId(${toTypeScriptPomPatternExpression(selector)}, ${locatorDescription});`);
writer.writeLine(`this.recordPomAction(${JSON.stringify(componentName)}, ${JSON.stringify(methodName)}, [${toTypeScriptPomPatternExpression(selector)}]);`);
writer.writeLine("await this.clickLocator(locator);");
writer.writeLine(`return new ${target}(this.page);`);
});
writer.writeLine(");");
},
}),
];
}
export function generateViewObjectModelMembers(
componentName: string | undefined,
targetPageObjectModelClass: string | undefined,
methodName: string,
nativeRole: string,
selector: PomStringPattern,
alternateSelectors: PomStringPattern[] | undefined,
getterNameOverride: string | undefined,
parameters: PomParameterSpec[],
): TypeScriptClassMember[] {
const baseMethodName = (nativeRole === "radio")
? (methodName || "Radio")
: methodName;
const members = generateGetElementByDataTestId(
componentName,
baseMethodName,
nativeRole,
selector,
alternateSelectors,
getterNameOverride,
parameters,
);
if (targetPageObjectModelClass) {
return [
...members,
...generateNavigationMethod({
componentName,
targetPageObjectModelClass,
baseMethodName,
selector,
alternateSelectors,
parameters,
}),
];
}
if (nativeRole === "select") {
return [...members, ...generateSelectMethod(componentName, baseMethodName, selector, parameters)];
}
if (nativeRole === "vselect") {
return [...members, ...generateVSelectMethod(componentName, baseMethodName, selector, parameters)];
}
if (nativeRole === "input") {
return [...members, ...generateTypeMethod(componentName, baseMethodName, selector, parameters)];
}
if (nativeRole === "radio") {
return [...members, ...generateRadioMethod(componentName, baseMethodName || "Radio", selector, parameters)];
}
return [...members, ...generateClickMethod(componentName, baseMethodName, nativeRole, selector, alternateSelectors, parameters)];
}
export function generateViewObjectModelMethodContent(
componentName: string | undefined,
targetPageObjectModelClass: string | undefined,
methodName: string,
nativeRole: string,
selector: PomStringPattern,
alternateSelectors: PomStringPattern[] | undefined,
getterNameOverride: string | undefined,
parameters: PomParameterSpec[],
) {
return renderClassMembers(
generateViewObjectModelMembers(
componentName,
targetPageObjectModelClass,
methodName,
nativeRole,
selector,
alternateSelectors,
getterNameOverride,
parameters,
),
);
}