Convert e2e-pw CJS utils and barrel index to TypeScript#63318
Convert e2e-pw CJS utils and barrel index to TypeScript#63318adimoldovan merged 17 commits intotrunkfrom
Conversation
Rename 13 utility files to TypeScript extension to preserve git history before converting the content.
|
No actionable comments were generated in the recent review. 🎉 📝 WalkthroughWalkthroughE2E test utilities under plugins/woocommerce/tests/e2e-pw/utils/ were converted from CommonJS JavaScript to TypeScript ES modules: JS files removed, .ts equivalents added, functions received type annotations, exports switched to named ES exports, and a new Changes
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
🚥 Pre-merge checks | ✅ 3✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
plugins/woocommerce/tests/e2e-pw/utils/wordpress.ts (2)
31-33:⚠️ Potential issue | 🟡 MinorPotential null dereference in chained
.find().match()[0].If no version in the API response has
'latest'status,.find()returnsundefinedand.match()throws. Similarly, if the version string doesn't match the regex,.match()returnsnulland[0]throws.This is pre-existing logic, but since you're converting to TypeScript, the compiler may flag this depending on
strictNullChecks. Worth adding a guard.🛡️ Suggested defensive approach
- const latestMajorAndMinorNumbers = allVersions - .find( ( version ) => body[ version ] === 'latest' ) - .match( /^\d+.\d+/ )[ 0 ]; + const latestVersion = allVersions.find( + ( version ) => body[ version ] === 'latest' + ); + if ( ! latestVersion ) { + throw new Error( 'No latest WordPress version found in API response' ); + } + const match = latestVersion.match( /^\d+\.\d+/ ); + if ( ! match ) { + throw new Error( `Unexpected version format: ${ latestVersion }` ); + } + const latestMajorAndMinorNumbers = match[ 0 ];Note: the regex
/^\d+.\d+/also uses an unescaped.which matches any character, not just a literal dot. Should be\.— though in practice this won't cause incorrect matches for version strings.
49-53:⚠️ Potential issue | 🟡 Minor
errorincatchis typedunknownunder strict TypeScript.With
strict: truein the tsconfig,useUnknownInCatchVariablesdefaults to enabled (TypeScript 4.4+). Accessingerror.messagedirectly will fail to compile becauseerroris typed asunknown.Suggested fix
} catch ( error ) { throw new Error( - `Error getting WordPress version: ${ error.message }` + `Error getting WordPress version: ${ error instanceof Error ? error.message : error }` ); }
🤖 Fix all issues with AI agents
In `@plugins/woocommerce/tests/e2e-pw/utils/features.ts`:
- Around line 7-11: The request parameter in setFeatureFlag and
resetFeatureFlags is currently untyped; update both function signatures to type
request as APIRequestContext (importing APIRequestContext from `@playwright/test`
if not already imported) so they match sibling files like tours.ts and maintain
consistent type annotations across the converted tests.
In `@plugins/woocommerce/tests/e2e-pw/utils/variable-products.ts`:
- Around line 11-21: ProductAttribute and Variation are not exported, so
consumers importing the module (e.g., import * as variableProducts) cannot
access them; add the export keyword to the declarations for ProductAttribute and
Variation so they become public types available to other modules (update the
interface declarations named ProductAttribute and Variation to be exported).
🧹 Nitpick comments (4)
plugins/woocommerce/tests/e2e-pw/utils/payments-settings.ts (1)
14-15: Useconsole.errorfor error output.Errors should go to stderr via
console.errorrather thanconsole.logso they're distinguishable in CI logs.Suggested fix
} catch ( error ) { - console.log( error ); + console.error( error ); }plugins/woocommerce/tests/e2e-pw/utils/coming-soon.ts (1)
18-22: Consider re-throwing after logging to surface setup failures.The
catchblock swallows the error, so callers have no signal that the "coming soon" option wasn't set. A silently failed precondition can cause misleading downstream test failures that are hard to diagnose.♻️ Suggested improvement
try { await setOption( request, baseURL, 'woocommerce_coming_soon', enabled ); } catch ( error ) { console.log( error ); + throw error; }plugins/woocommerce/tests/e2e-pw/utils/variable-products.ts (1)
190-196:combineinner function parameters have implicitanytypes.
runningListandnextAttributeare untyped function parameters, which will be implicitlyanyunder strict TypeScript. This is pre-existing complexity from the JS version, but since the PR adds type annotations to all other function parameters, these stand out. Consider typing them in a follow-up ifnoImplicitAnyis enabled or planned.plugins/woocommerce/tests/e2e-pw/utils/cli.ts (1)
9-15: Shell command injection risk via unsanitizedcommandparameter.
execspawns a shell, andcommandis interpolated directly into the string. Any shell metacharacters incommand(;,|,$(), etc.) would be interpreted. While callers are internal test code today, the coding guidelines require guarding against unexpected inputs.A safer alternative would be
execFile(no shell) or at minimum a basic validation/allowlist on the command string. Since this is test-only utility code, this is low-priority but worth being aware of.
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (2)
plugins/woocommerce/tests/e2e-pw/utils/variable-products.ts (2)
26-26: Module-level mutableproductIds— acceptable for test utilities but worth a note.The shared mutable array accumulates IDs across calls, and
deleteProductsAddedByTestsclears them via the API but never resets the array itself. If tests calldeleteProductsAddedByTestsand then create more products, the array will still contain the old (now-deleted) IDs alongside the new ones, causing a redundant (or failing) delete on the next cleanup call. This is likely fine in practice given test isolation, just calling it out.Also applies to: 119-131, 137-139
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@plugins/woocommerce/tests/e2e-pw/utils/variable-products.ts` at line 26, The module-level mutable array productIds retains deleted IDs causing redundant/failing cleanup; update the cleanup routine deleteProductsAddedByTests (and any other functions that clear via API) to also reset the in-memory array (e.g., productIds.length = 0 or assign a new empty array) after successful deletion, and ensure any functions that push to productIds (the helpers that create test products) continue to push fresh IDs; this guarantees productIds doesn't accumulate stale IDs across test runs.
189-228: Thecombinehelper has an inconsistent return shape whenattributeshas only one element.When
attributes.length === 1,generateVariationsFromAttributesreturnsstring[](the raw options), but with 2+ attributes it returnsstring[][]. The declared type ofallVariations(string[] | string[][]) accurately reflects this, but callers must handle both shapes — which is error-prone.This is pre-existing behavior from the JS version, so not blocking, but worth noting for a future cleanup: you could normalize the single-attribute case to return
string[][](e.g.,attributes[0].options.map(o => [o])) so the return type is alwaysstring[][].Also,
attributes[0].optionson line 220 will throw if called with an empty array. A guard would make this safer, though admittedly this is a test utility with controlled inputs.♻️ Optional: normalize the initial value so the return type is always `string[][]`
- let allVariations: string[] | string[][] = attributes[ 0 ].options; + if ( attributes.length === 0 ) { + return []; + } + + let allVariations: string[][] = attributes[ 0 ].options.map( ( o ) => [ o ] ); for ( let i = 1; i < attributes.length; i++ ) { const nextAttribute = attributes[ i ].options; allVariations = combine( allVariations, nextAttribute ); }This would also let you simplify
combineto always acceptstring[][], removing the union type and the normalization branch.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@plugins/woocommerce/tests/e2e-pw/utils/variable-products.ts` around lines 189 - 228, generateVariationsFromAttributes returns inconsistent shapes: when attributes.length === 1 it returns string[] (raw options) but for 2+ attributes it returns string[][]; also attributes[0].options will throw if attributes is empty. Fix by normalizing the initial value and combine signature: convert the single-attribute case into an array-of-arrays (e.g. map options to [o]) so allVariations is always string[][], simplify combine to accept string[][] and always return string[][], and add a guard at the start of generateVariationsFromAttributes to handle or early-return when attributes is empty.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@plugins/woocommerce/tests/e2e-pw/utils/wordpress.ts`:
- Around line 43-47: latestMinus1 (result of previousStableVersions.find) can be
undefined and is passed to core.setOutput('version', latestMinus1); update the
logic around previousStableVersions and latestMinus1 to handle the undefined
case: after computing latestMinus1 validate it (e.g., if (!latestMinus1) throw
an Error or set a sensible fallback string) before calling core.setOutput;
reference the variables latestMinus1, previousStableVersions and the call to
core.setOutput to locate and change the behavior so a missing version does not
pass undefined downstream.
- Line 57: The catch clause in the try/catch uses a concrete type (catch (error:
Error)) which TypeScript disallows; change it to use catch (error: unknown) (or
catch (error: any)) in plugins/woocommerce/tests/e2e-pw/utils/wordpress.ts, and
if you need Error properties later, narrow it inside the catch (e.g., via
instanceof Error) before accessing message/stack so the code compiles and
remains type-safe.
---
Nitpick comments:
In `@plugins/woocommerce/tests/e2e-pw/utils/variable-products.ts`:
- Line 26: The module-level mutable array productIds retains deleted IDs causing
redundant/failing cleanup; update the cleanup routine deleteProductsAddedByTests
(and any other functions that clear via API) to also reset the in-memory array
(e.g., productIds.length = 0 or assign a new empty array) after successful
deletion, and ensure any functions that push to productIds (the helpers that
create test products) continue to push fresh IDs; this guarantees productIds
doesn't accumulate stale IDs across test runs.
- Around line 189-228: generateVariationsFromAttributes returns inconsistent
shapes: when attributes.length === 1 it returns string[] (raw options) but for
2+ attributes it returns string[][]; also attributes[0].options will throw if
attributes is empty. Fix by normalizing the initial value and combine signature:
convert the single-attribute case into an array-of-arrays (e.g. map options to
[o]) so allVariations is always string[][], simplify combine to accept
string[][] and always return string[][], and add a guard at the start of
generateVariationsFromAttributes to handle or early-return when attributes is
empty.
Testing GuidelinesHi @adimoldovan , Apart from reviewing the code changes, please make sure to review the testing instructions (Guide) and verify that relevant tests (E2E, Unit, Integration, etc.) have been added or updated as needed. Reminder: PR reviewers are required to document testing performed. This includes:
|
Submission Review Guidelines:
Changes proposed in this Pull Request:
This is the ninth PR in the series to convert the WooCommerce
e2e-pwtests from JavaScript to TypeScript, building on the scaffolding introduced in #63188.Changes:
utils/:cli.ts,coming-soon.ts,editor.ts,features.ts,helpers.ts,login.ts,payments-settings.ts,product-block-editor.ts,simple-products.ts,tours.ts,variable-products.ts,wordpress.tsindex.jstoindex.ts— CJSrequire→ ESMimport * as,module.exports→exportrequire→import,module.exports→export)ProductAttributeandVariationextracted from JSDoc types invariable-products.tsfor reuse across multiple functions@woocommerce/dependency-groupESLint ruleConversion approach:
Each file was renamed from
.jsto.tsviagit mvin a dedicated rename commit, then content changes (type annotations, CJS→ESM) were applied in a separate commit. This preservesgit log --followhistory andgit blameattribution.PR series plan:
tsconfig.json, ESLint config)How to test the changes in this Pull Request:
Follow the instructions in the
plugins/woocommerce/tests/e2e-pw/README.mdfile.Testing that has already taken place:
.tsfiles pass ESLint with zero errors (warnings only forimport/no-extraneous-dependenciespackage resolution).Milestone
Changelog entry
Changelog Entry Details
Significance
Type
Message
Convert e2e-pw CJS utils and barrel index to TypeScript.