From f095bbb67bac7e1a7782683a62ab5daa366797d2 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 24 Oct 2026 11:07:48 +0000 Subject: [PATCH 1/6] Type-check and format-check the test suites in CI - Type check (new CI job): the join form and its Jest tests, and the E2E tests, which gain a tsconfig. Both already passed; CI didn't run either. `npm run typecheck` runs both. - Prettier now checks packages/join-e2e as well as packages/join-flow. The E2E package gets its own settings matching how its tests were written (single quotes, 120 columns, trailing commas), so formatting it is a small change rather than a restyle. - phpcs and PHPStan now cover the PHPUnit tests. phpcs allows snake_case method names there (test doubles mirror WordPress's $wpdb API); its other findings were whitespace, fixed with phpcbf. PHPStan's three findings are fixed: an unused property, a Mockery double typed as wpdb, and resetting Stripe's HTTP client to its default rather than null. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BL2bFrTk84JMy3CPAsCTV9 --- .github/workflows/jest-tests.yml | 28 ++++++++++- .prettierignore | 4 +- package.json | 3 +- packages/join-block/phpcs.xml | 7 ++- packages/join-block/phpstan.neon | 1 + .../tests/JoinServiceFreeMembershipTest.php | 8 ++- .../tests/JoinServiceMailchimpTest.php | 8 ++- .../tests/MailchimpServiceTagsTest.php | 8 ++- .../tests/SessionLockTestProcess.php | 4 +- .../tests/SettingsComputeTagsToRemoveTest.php | 3 -- .../SettingsMembershipPlanLookupTest.php | 1 + .../tests/StripeInvoicePaidTest.php | 11 ++-- .../join-block/tests/StripeWebhookTest.php | 4 +- packages/join-e2e/.prettierrc.json | 5 ++ packages/join-e2e/fake-api/server.js | 17 +++++-- packages/join-e2e/package-lock.json | 35 ++++++++++++- packages/join-e2e/package.json | 7 ++- .../tests/admin-plan-redirect.spec.ts | 26 +++++----- .../join-e2e/tests/free-membership.spec.ts | 4 +- packages/join-e2e/tests/helpers.ts | 10 +--- packages/join-e2e/tests/settings/copy.spec.ts | 17 +++++-- packages/join-e2e/tests/settings/fake-api.ts | 5 +- .../settings/features-integrations.spec.ts | 7 ++- .../join-e2e/tests/settings/features.spec.ts | 5 +- .../tests/settings/integrations-crm.spec.ts | 6 +-- .../settings/integrations-logging.spec.ts | 16 +++--- .../settings/integrations-payments.spec.ts | 50 +++++++++++++++---- .../tests/settings/logging-debug.spec.ts | 15 +++++- .../tests/settings/membership-plans.spec.ts | 35 +++++++++---- .../join-e2e/tests/settings/theme.spec.ts | 11 ++-- .../tests/supporter-mode-edge-cases.spec.ts | 8 +-- packages/join-e2e/tsconfig.json | 15 ++++++ readme.md | 11 ++-- 33 files changed, 295 insertions(+), 100 deletions(-) create mode 100644 packages/join-e2e/.prettierrc.json create mode 100644 packages/join-e2e/tsconfig.json diff --git a/.github/workflows/jest-tests.yml b/.github/workflows/jest-tests.yml index 3f5021f0..57cbb05e 100644 --- a/.github/workflows/jest-tests.yml +++ b/.github/workflows/jest-tests.yml @@ -41,4 +41,30 @@ jobs: run: npm ci --ignore-scripts - name: Check formatting - run: npx prettier --check packages/join-flow + run: npx prettier --check packages/join-flow packages/join-e2e + + typecheck: + name: Type check + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-node@v4 + with: + node-version: '20' + + # The postinstall installs join-flow's dependencies, which its type + # check needs. + - name: Install root deps + run: npm ci + + - name: Type check the join form and its Jest tests + run: npx tsc --noEmit -p packages/join-flow + + - name: Install E2E deps + working-directory: packages/join-e2e + run: npm ci + + - name: Type check the E2E tests + working-directory: packages/join-e2e + run: npm run typecheck diff --git a/.prettierignore b/.prettierignore index c5e79c1c..032e8135 100644 --- a/.prettierignore +++ b/.prettierignore @@ -1,2 +1,4 @@ packages/join-flow/build -packages/join-flow/dist \ No newline at end of file +packages/join-flow/dist +packages/join-e2e/test-results +packages/join-e2e/playwright-report diff --git a/package.json b/package.json index 1224b1d6..e2fc8456 100644 --- a/package.json +++ b/package.json @@ -11,7 +11,8 @@ "build": "npm --prefix packages/join-flow run build", "dist": "npm run build && scripts/package.sh", "deploy": "npm run build && sh scripts/deploy.sh", - "prettier": "prettier --write packages/join-flow" + "prettier": "prettier --write packages/join-flow packages/join-e2e", + "typecheck": "tsc --noEmit -p packages/join-flow && npm --prefix packages/join-e2e run typecheck" }, "devDependencies": { "prettier": "^3.9.10", diff --git a/packages/join-block/phpcs.xml b/packages/join-block/phpcs.xml index ba5130f9..dcfb0cea 100644 --- a/packages/join-block/phpcs.xml +++ b/packages/join-block/phpcs.xml @@ -4,7 +4,6 @@ . vendor/* - tests/* wordpress/* @@ -18,6 +17,12 @@ + + + tests/* + + diff --git a/packages/join-block/phpstan.neon b/packages/join-block/phpstan.neon index 8a22e424..b5e7c210 100644 --- a/packages/join-block/phpstan.neon +++ b/packages/join-block/phpstan.neon @@ -6,6 +6,7 @@ parameters: paths: - src - join.php + - tests scanDirectories: - vendor - wordpress diff --git a/packages/join-block/tests/JoinServiceFreeMembershipTest.php b/packages/join-block/tests/JoinServiceFreeMembershipTest.php index ee4818f4..2dc0d2da 100644 --- a/packages/join-block/tests/JoinServiceFreeMembershipTest.php +++ b/packages/join-block/tests/JoinServiceFreeMembershipTest.php @@ -148,10 +148,14 @@ public function get_results(string $query, $output = null): array public array $errors = []; // phpcs:ignore PSR1.Methods.CamelCapsMethodName.NotCamelCaps - public function info(string $msg, array $ctx = []): void {} + public function info(string $msg, array $ctx = []): void + { + } // phpcs:ignore PSR1.Methods.CamelCapsMethodName.NotCamelCaps - public function warning(string $msg, array $ctx = []): void {} + public function warning(string $msg, array $ctx = []): void + { + } // phpcs:ignore PSR1.Methods.CamelCapsMethodName.NotCamelCaps public function error(string $msg, array $ctx = []): void diff --git a/packages/join-block/tests/JoinServiceMailchimpTest.php b/packages/join-block/tests/JoinServiceMailchimpTest.php index 43755bcc..ce014417 100644 --- a/packages/join-block/tests/JoinServiceMailchimpTest.php +++ b/packages/join-block/tests/JoinServiceMailchimpTest.php @@ -122,10 +122,14 @@ public function get_results(string $query, $output = null): array public array $errors = []; // phpcs:ignore PSR1.Methods.CamelCapsMethodName.NotCamelCaps - public function info(string $msg, array $ctx = []): void {} + public function info(string $msg, array $ctx = []): void + { + } // phpcs:ignore PSR1.Methods.CamelCapsMethodName.NotCamelCaps - public function warning(string $msg, array $ctx = []): void {} + public function warning(string $msg, array $ctx = []): void + { + } // phpcs:ignore PSR1.Methods.CamelCapsMethodName.NotCamelCaps public function error(string $msg, array $ctx = []): void diff --git a/packages/join-block/tests/MailchimpServiceTagsTest.php b/packages/join-block/tests/MailchimpServiceTagsTest.php index 627ab61d..1fdfc036 100644 --- a/packages/join-block/tests/MailchimpServiceTagsTest.php +++ b/packages/join-block/tests/MailchimpServiceTagsTest.php @@ -39,10 +39,14 @@ protected function setUp(): void public array $errors = []; // phpcs:ignore PSR1.Methods.CamelCapsMethodName.NotCamelCaps - public function info(string $msg, array $ctx = []): void {} + public function info(string $msg, array $ctx = []): void + { + } // phpcs:ignore PSR1.Methods.CamelCapsMethodName.NotCamelCaps - public function warning(string $msg, array $ctx = []): void {} + public function warning(string $msg, array $ctx = []): void + { + } // phpcs:ignore PSR1.Methods.CamelCapsMethodName.NotCamelCaps public function error(string $msg, array $ctx = []): void diff --git a/packages/join-block/tests/SessionLockTestProcess.php b/packages/join-block/tests/SessionLockTestProcess.php index bc9a14e6..9ee5e192 100644 --- a/packages/join-block/tests/SessionLockTestProcess.php +++ b/packages/join-block/tests/SessionLockTestProcess.php @@ -3,8 +3,8 @@ require_once(__DIR__ . "/../vendor/autoload.php"); // Load WordPress functions required by JoinService::acquireLock() -define( 'ABSPATH', __DIR__ . '/../wordpress/' ); -define( 'WPINC', 'wp-includes' ); +define('ABSPATH', __DIR__ . '/../wordpress/'); +define('WPINC', 'wp-includes'); require_once(__DIR__ . "/../wordpress/wp-includes/formatting.php"); require_once(__DIR__ . "/../wordpress/wp-includes/functions.php"); diff --git a/packages/join-block/tests/SettingsComputeTagsToRemoveTest.php b/packages/join-block/tests/SettingsComputeTagsToRemoveTest.php index 3074debf..519b6002 100644 --- a/packages/join-block/tests/SettingsComputeTagsToRemoveTest.php +++ b/packages/join-block/tests/SettingsComputeTagsToRemoveTest.php @@ -23,9 +23,6 @@ class SettingsComputeTagsToRemoveTest extends TestCase /** Values returned by the carbon_get_theme_option stub, keyed by field name. */ private array $settings = []; - /** Plan rows returned by the $wpdb stub, as stored in wp_options. */ - private array $storedPlans = []; - protected function setUp(): void { parent::setUp(); diff --git a/packages/join-block/tests/SettingsMembershipPlanLookupTest.php b/packages/join-block/tests/SettingsMembershipPlanLookupTest.php index 1d18cd7c..e32b1851 100644 --- a/packages/join-block/tests/SettingsMembershipPlanLookupTest.php +++ b/packages/join-block/tests/SettingsMembershipPlanLookupTest.php @@ -160,6 +160,7 @@ public function testReturnsFalsyWhenNoStoredPlanMatches(): void private function stubWpdbWithRows(array $rows): void { global $wpdb; + /** @var \wpdb&\Mockery\MockInterface $wpdb */ $wpdb = Mockery::mock(); $wpdb->options = 'wp_options'; $wpdb->shouldReceive('esc_like')->andReturnUsing(fn($s) => $s); diff --git a/packages/join-block/tests/StripeInvoicePaidTest.php b/packages/join-block/tests/StripeInvoicePaidTest.php index 0ae85f1c..e868ecb5 100644 --- a/packages/join-block/tests/StripeInvoicePaidTest.php +++ b/packages/join-block/tests/StripeInvoicePaidTest.php @@ -33,10 +33,14 @@ protected function setUp(): void public array $errors = []; // phpcs:ignore PSR1.Methods.CamelCapsMethodName.NotCamelCaps - public function info(string $msg, array $ctx = []): void {} + public function info(string $msg, array $ctx = []): void + { + } // phpcs:ignore PSR1.Methods.CamelCapsMethodName.NotCamelCaps - public function warning(string $msg, array $ctx = []): void {} + public function warning(string $msg, array $ctx = []): void + { + } // phpcs:ignore PSR1.Methods.CamelCapsMethodName.NotCamelCaps public function error(string $msg, array $ctx = []): void @@ -52,7 +56,8 @@ protected function tearDown(): void { global $joinBlockLog; $joinBlockLog = null; - \Stripe\ApiRequestor::setHttpClient(null); + // Back to the client Stripe uses by default. + \Stripe\ApiRequestor::setHttpClient(\Stripe\HttpClient\CurlClient::instance()); Monkey\tearDown(); parent::tearDown(); } diff --git a/packages/join-block/tests/StripeWebhookTest.php b/packages/join-block/tests/StripeWebhookTest.php index 201675f4..9e2f41d7 100644 --- a/packages/join-block/tests/StripeWebhookTest.php +++ b/packages/join-block/tests/StripeWebhookTest.php @@ -200,8 +200,8 @@ public function testResolveTierTagChangesSharedTagsAreNotRemoved(): void $result = $this->callResolveTierTagChanges($newPlan, $oldPlan); $this->assertContains('high-wage', $result['addTags']); - $this->assertContains('member', $result['addTags']); - $this->assertContains('low-wage', $result['removeTags']); + $this->assertContains('member', $result['addTags']); + $this->assertContains('low-wage', $result['removeTags']); $this->assertNotContains('member', $result['removeTags'], 'member must not be removed when it is also being added'); } diff --git a/packages/join-e2e/.prettierrc.json b/packages/join-e2e/.prettierrc.json new file mode 100644 index 00000000..dc8c7109 --- /dev/null +++ b/packages/join-e2e/.prettierrc.json @@ -0,0 +1,5 @@ +{ + "singleQuote": true, + "printWidth": 120, + "trailingComma": "all" +} diff --git a/packages/join-e2e/fake-api/server.js b/packages/join-e2e/fake-api/server.js index 61a0e079..98afcf8e 100644 --- a/packages/join-e2e/fake-api/server.js +++ b/packages/join-e2e/fake-api/server.js @@ -102,14 +102,22 @@ function fakeStripe(method, url, body) { } if (method === 'POST' && !idOrAction) { stripe.counter += 1; - const object = { id: `${prefix}_e2e_${stripe.counter}`, object: type.replace(/s$/, ''), active: true, livemode: false, ...body }; + const object = { + id: `${prefix}_e2e_${stripe.counter}`, + object: type.replace(/s$/, ''), + active: true, + livemode: false, + ...body, + }; if (body && body.unit_amount) object.unit_amount = Number(body.unit_amount); store.push(object); return { status: 200, body: object }; } if (method === 'GET' && idOrAction) { const object = store.find((candidate) => candidate.id === idOrAction); - return object ? { status: 200, body: object } : { status: 404, body: { error: { type: 'invalid_request_error', message: 'No such object' } } }; + return object + ? { status: 200, body: object } + : { status: 404, body: { error: { type: 'invalid_request_error', message: 'No such object' } } }; } return null; } @@ -227,7 +235,10 @@ function handleControl(request, response) { const certs = path.join(__dirname, 'certs'); https - .createServer({ key: fs.readFileSync(path.join(certs, 'server.key')), cert: fs.readFileSync(path.join(certs, 'server.crt')) }, handleService) + .createServer( + { key: fs.readFileSync(path.join(certs, 'server.key')), cert: fs.readFileSync(path.join(certs, 'server.crt')) }, + handleService, + ) .listen(443); http.createServer(handleService).listen(80); http.createServer(handleControl).listen(8080); diff --git a/packages/join-e2e/package-lock.json b/packages/join-e2e/package-lock.json index f35d0d8f..e2c78ab5 100644 --- a/packages/join-e2e/package-lock.json +++ b/packages/join-e2e/package-lock.json @@ -8,7 +8,9 @@ "name": "@ck/join-e2e", "version": "1.0.0", "devDependencies": { - "@playwright/test": "^1.63.0" + "@playwright/test": "^1.63.0", + "@types/node": "^22.20.5", + "typescript": "^5.9.3" } }, "node_modules/@playwright/test": { @@ -27,6 +29,16 @@ "node": ">=20" } }, + "node_modules/@types/node": { + "version": "22.20.5", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.5.tgz", + "integrity": "sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~6.21.0" + } + }, "node_modules/playwright": { "version": "1.63.0", "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.63.0.tgz", @@ -55,6 +67,27 @@ "engines": { "node": ">=20" } + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/undici-types": { + "version": "6.21.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", + "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", + "dev": true, + "license": "MIT" } } } diff --git a/packages/join-e2e/package.json b/packages/join-e2e/package.json index 59666123..ba3aabc8 100644 --- a/packages/join-e2e/package.json +++ b/packages/join-e2e/package.json @@ -8,9 +8,12 @@ "env:start": "bash scripts/env.sh start", "env:stop": "bash scripts/env.sh stop", "env:destroy": "bash scripts/env.sh destroy", - "pretest": "bash scripts/seed.sh" + "pretest": "bash scripts/seed.sh", + "typecheck": "tsc --noEmit -p ." }, "devDependencies": { - "@playwright/test": "^1.63.0" + "@playwright/test": "^1.63.0", + "@types/node": "^22.20.5", + "typescript": "^5.9.3" } } diff --git a/packages/join-e2e/tests/admin-plan-redirect.spec.ts b/packages/join-e2e/tests/admin-plan-redirect.spec.ts index e5923517..3679cb90 100644 --- a/packages/join-e2e/tests/admin-plan-redirect.spec.ts +++ b/packages/join-e2e/tests/admin-plan-redirect.spec.ts @@ -35,9 +35,7 @@ const REDIRECT_CHECKBOX = 'Redirect to a page instead of taking payment'; function field(scope: Locator, label: string): Locator { // One selector rather than a `has` filter, so it also works inside the // block editor's iframe. - return scope - .locator(`.cf-field:not(.cf-separator):has(.cf-field__label:text-matches("^${label}[*]?$"))`) - .first(); + return scope.locator(`.cf-field:not(.cf-separator):has(.cf-field__label:text-matches("^${label}[*]?$"))`).first(); } /** The CK Join Form block. The block editor renders its content in an iframe. */ @@ -92,7 +90,12 @@ async function openNewPageWithJoinBlock(page: Page): Promise { // New pages open with WordPress's starter pattern picker over the editor. const patterns = page.getByRole('dialog', { name: 'Choose a pattern' }); - if (await patterns.waitFor({ state: 'visible', timeout: 5000 }).then(() => true, () => false)) { + if ( + await patterns.waitFor({ state: 'visible', timeout: 5000 }).then( + () => true, + () => false, + ) + ) { await patterns.getByRole('button', { name: 'Close' }).click(); } @@ -217,9 +220,9 @@ test.describe('Redirect help text', () => { await openNewPageWithJoinBlock(page); const plansField = field(joinFormBlock(page), 'Custom Membership Plans'); await plansField.locator('.cf-complex__inserter-button').click(); - await expect( - plansField.locator('.cf-field.cf-checkbox', { hasText: REDIRECT_CHECKBOX }).first(), - ).toContainText(NOT_RECORDED); + await expect(plansField.locator('.cf-field.cf-checkbox', { hasText: REDIRECT_CHECKBOX }).first()).toContainText( + NOT_RECORDED, + ); } finally { setCrms(false); } @@ -235,14 +238,13 @@ test.describe('Custom plans in the CK Join Form block', () => { // Same as above, but picks the page without the picker's search, so the // redirect itself stays covered while JOIN-158 is open. - test('a redirecting plan set up in the block editor redirects on the published page, picking the page from the full list', async ({ page }) => { + test('a redirecting plan set up in the block editor redirects on the published page, picking the page from the full list', async ({ + page, + }) => { await redirectingPlanInBlockEditor(page, pickRedirectTargetFromList); }); - async function redirectingPlanInBlockEditor( - page: Page, - choose: (picker: Locator) => Promise, - ): Promise { + async function redirectingPlanInBlockEditor(page: Page, choose: (picker: Locator) => Promise): Promise { await loginAsAdmin(page); await openNewPageWithJoinBlock(page); diff --git a/packages/join-e2e/tests/free-membership.spec.ts b/packages/join-e2e/tests/free-membership.spec.ts index 89da1436..ee21e794 100644 --- a/packages/join-e2e/tests/free-membership.spec.ts +++ b/packages/join-e2e/tests/free-membership.spec.ts @@ -27,9 +27,7 @@ test.beforeEach(async ({ page }) => { }); test.describe('Confirm stage reached without payment', () => { - test('continuing through Details and Plan skips payment and shows confirm stage', async ({ - page, - }) => { + test('continuing through Details and Plan skips payment and shows confirm stage', async ({ page }) => { // Intercept the /join endpoint so the confirm page does not error on submit. await page.route('**/wp-json/join/v1/join', async (route) => { await route.fulfill({ diff --git a/packages/join-e2e/tests/helpers.ts b/packages/join-e2e/tests/helpers.ts index b09c10b6..e8c5c000 100644 --- a/packages/join-e2e/tests/helpers.ts +++ b/packages/join-e2e/tests/helpers.ts @@ -65,10 +65,7 @@ export async function injectEnvOverrides( * Call this after the form has advanced past the details stage (so that * sessionStorage already contains the accumulated form data). */ -export async function captureJoinBodyViaStripeRedirect( - page: Page, - pageUrl: string, -): Promise> { +export async function captureJoinBodyViaStripeRedirect(page: Page, pageUrl: string): Promise> { // Inject the fake payment intent ID into the existing session state. await page.evaluate((key: string) => { const state = JSON.parse(sessionStorage.getItem(key) || '{}'); @@ -91,10 +88,7 @@ export async function captureJoinBodyViaStripeRedirect( await page.goto(`${pageUrl}?stripe_success=true`); // Wait for the confirm page heading to appear. - await page.waitForFunction( - () => document.querySelector('h2') !== null, - { timeout: 10000 }, - ); + await page.waitForFunction(() => document.querySelector('h2') !== null, { timeout: 10000 }); // Poll until /join fires — the confirm page auto-submits on mount and the // POST may arrive slightly after the heading renders. diff --git a/packages/join-e2e/tests/settings/copy.spec.ts b/packages/join-e2e/tests/settings/copy.spec.ts index 926ef460..a73a0226 100644 --- a/packages/join-e2e/tests/settings/copy.spec.ts +++ b/packages/join-e2e/tests/settings/copy.spec.ts @@ -258,16 +258,22 @@ test.describe('Details step', () => { test('Privacy Copy', async ({ settings, page }) => { await settings.open('Copy'); - await settings.setRichText('Privacy Copy', '

Read our privacy policy.

'); + await settings.setRichText( + 'Privacy Copy', + '

Read our privacy policy.

', + ); await settings.save(); await openJoinForm(page); - await expect(page.getByRole('link', { name: 'privacy policy' })).toHaveAttribute('href', 'https://example.org/privacy'); + await expect(page.getByRole('link', { name: 'privacy policy' })).toHaveAttribute( + 'href', + 'https://example.org/privacy', + ); }); }); test.describe('Plan step', () => { - test('Membership Tiers Heading and Copy, with the copy\'s built-in default', async ({ settings, page }) => { + test("Membership Tiers Heading and Copy, with the copy's built-in default", async ({ settings, page }) => { expect(getSetting('membership_tiers_copy')).toBe(''); await goToPlans(page); await expect(page.getByText('You can change or cancel whenever you want.')).toBeVisible(); @@ -296,7 +302,10 @@ test.describe('Plan step', () => { }); // Linear JOIN-163: passed to the form, but nothing in the form shows it. - test.fixme('"Only valid for monthly subscriptions" (day of month copy) labels the payment day', async ({ settings, page }) => { + test.fixme('"Only valid for monthly subscriptions" (day of month copy) labels the payment day', async ({ + settings, + page, + }) => { await settings.open('Copy'); await settings.setText('Only valid for monthly subscriptions', 'Which day should we take payment?'); await settings.save(); diff --git a/packages/join-e2e/tests/settings/fake-api.ts b/packages/join-e2e/tests/settings/fake-api.ts index fa87a747..d13693de 100644 --- a/packages/join-e2e/tests/settings/fake-api.ts +++ b/packages/join-e2e/tests/settings/fake-api.ts @@ -56,6 +56,9 @@ export async function overrideFakeApi(rule: { * Puts an object straight into the fake Stripe, as if it had been created * there earlier, e.g. seedFakeStripe('customers', { id: 'cus_1', email: '...' }). */ -export async function seedFakeStripe(type: 'products' | 'prices' | 'customers' | 'subscriptions' | 'invoices', object: Record): Promise { +export async function seedFakeStripe( + type: 'products' | 'prices' | 'customers' | 'subscriptions' | 'invoices', + object: Record, +): Promise { await control('POST', `/stripe/${type}`, object); } diff --git a/packages/join-e2e/tests/settings/features-integrations.spec.ts b/packages/join-e2e/tests/settings/features-integrations.spec.ts index 31e21239..bf70d2bb 100644 --- a/packages/join-e2e/tests/settings/features-integrations.spec.ts +++ b/packages/join-e2e/tests/settings/features-integrations.spec.ts @@ -188,7 +188,7 @@ test.describe('Payment providers', () => { await expect(logo(page, 'Stripe')).toBeVisible(); }); - test('Use GoCardless sends Direct Debit members to GoCardless\'s hosted pages', async ({ settings, page }) => { + test("Use GoCardless sends Direct Debit members to GoCardless's hosted pages", async ({ settings, page }) => { await settings.open('Features'); await settings.enableIntegration('Use GoCardless'); await settings.save(); @@ -232,7 +232,10 @@ test.describe('Payment providers', () => { expect(redirected).toBe(false); }); - test('Use Chargebee shows the Chargebee logo and sets Chargebee up with the site and publishable key', async ({ settings, page }) => { + test('Use Chargebee shows the Chargebee logo and sets Chargebee up with the site and publishable key', async ({ + settings, + page, + }) => { await settings.open('Features'); await settings.enableIntegration('Use Chargebee'); await settings.save(); diff --git a/packages/join-e2e/tests/settings/features.spec.ts b/packages/join-e2e/tests/settings/features.spec.ts index e82a1020..2087f9c9 100644 --- a/packages/join-e2e/tests/settings/features.spec.ts +++ b/packages/join-e2e/tests/settings/features.spec.ts @@ -243,7 +243,10 @@ test.describe('Enable international phone numbers', () => { await expect(page.getByText('Please enter a valid UK phone number')).toBeVisible(); }); - test('when on, a country code can be chosen and other countries\' numbers are accepted', async ({ settings, page }) => { + test("when on, a country code can be chosen and other countries' numbers are accepted", async ({ + settings, + page, + }) => { await settings.open('Features'); await settings.setCheckbox('Enable international phone numbers', true); await settings.save(); diff --git a/packages/join-e2e/tests/settings/integrations-crm.spec.ts b/packages/join-e2e/tests/settings/integrations-crm.spec.ts index cb0cf1d2..8c86e825 100644 --- a/packages/join-e2e/tests/settings/integrations-crm.spec.ts +++ b/packages/join-e2e/tests/settings/integrations-crm.spec.ts @@ -106,7 +106,7 @@ test.describe('Zetkin', () => { expect(await fakeApiRequests('api.dev.zetkin.org')).toEqual([]); }); - test('with the OAuth credentials, the member is added through Zetkin\'s API and tagged', async ({ + test("with the OAuth credentials, the member is added through Zetkin's API and tagged", async ({ settings, page, }) => { @@ -239,7 +239,7 @@ test.describe('Webhooks', () => { expect(await fakeApiRequests('fake-api')).toEqual([]); }); - test('Step Webhook Url is sent the form\'s data after each step', async ({ settings, page }) => { + test("Step Webhook Url is sent the form's data after each step", async ({ settings, page }) => { await settings.open('Integrations'); await settings.setText('Step Webhook Url', STEP_WEBHOOK); await settings.save(); @@ -259,7 +259,7 @@ test.describe('Webhooks', () => { }); test.describe('Auth0', () => { - test('a join creates the member\'s Auth0 account, with the credentials set here', async ({ settings, page }) => { + test("a join creates the member's Auth0 account, with the credentials set here", async ({ settings, page }) => { await settings.open('Features'); await settings.enableIntegration('Create Auth0 Account'); await settings.save(); diff --git a/packages/join-e2e/tests/settings/integrations-logging.spec.ts b/packages/join-e2e/tests/settings/integrations-logging.spec.ts index 9f0e1b31..2d9e8f6d 100644 --- a/packages/join-e2e/tests/settings/integrations-logging.spec.ts +++ b/packages/join-e2e/tests/settings/integrations-logging.spec.ts @@ -14,7 +14,9 @@ import { expect, fakeApiRequests, getSettings, joinFormEnv, openJoinForm, test, /** Makes the plugin log an info line ("Recording CK Join form step"). */ async function logSomething(request: APIRequestContext): Promise { - const response = await request.post('/wp-json/join/v1/step', { data: { email: 'someone@example.com', stage: 'details' } }); + const response = await request.post('/wp-json/join/v1/step', { + data: { email: 'someone@example.com', stage: 'details' }, + }); expect(response.ok()).toBe(true); } @@ -98,7 +100,7 @@ test.describe('Loggly', () => { test.describe('Sentry', () => { const DSN = 'https://e2epublickey@sentry.e2e.example/42'; - test('Sentry Dsn sends the plugin\'s errors to Sentry, and sets Sentry up in the join form', async ({ + test("Sentry Dsn sends the plugin's errors to Sentry, and sets Sentry up in the join form", async ({ settings, request, page, @@ -126,16 +128,18 @@ test.describe('Sentry', () => { return route.fulfill({ status: 200, body: '{}' }); }); await openJoinForm(page); - await page.evaluate(() => setTimeout(() => { - throw new Error('e2e form error'); - })); + await page.evaluate(() => + setTimeout(() => { + throw new Error('e2e form error'); + }), + ); await expect.poll(() => reported.length).toBeGreaterThan(0); expect(reported[0]).toContain('/api/42/'); }); }); test.describe('Google Cloud Logging', () => { - test('Google Cloud Project Id and Key File Contents send logs to that project\'s log', async ({ + test("Google Cloud Project Id and Key File Contents send logs to that project's log", async ({ settings, request, }) => { diff --git a/packages/join-e2e/tests/settings/integrations-payments.spec.ts b/packages/join-e2e/tests/settings/integrations-payments.spec.ts index c9e9beb4..e9d11490 100644 --- a/packages/join-e2e/tests/settings/integrations-payments.spec.ts +++ b/packages/join-e2e/tests/settings/integrations-payments.spec.ts @@ -101,7 +101,7 @@ test.describe('Stripe', () => { }); }); - test('Download Subscriptions exports Stripe\'s subscriptions as a spreadsheet', async ({ settings }) => { + test("Download Subscriptions exports Stripe's subscriptions as a spreadsheet", async ({ settings }) => { await settings.open('Features'); await settings.enableIntegration('Use Stripe'); await settings.save(); @@ -123,7 +123,10 @@ test.describe('Stripe', () => { status: 'active', created: 1767225600, current_period_end: 1769904000, - items: { object: 'list', data: [{ id: 'si_export', object: 'subscription_item', price: { id: 'price_export', object: 'price' } }] }, + items: { + object: 'list', + data: [{ id: 'si_export', object: 'subscription_item', price: { id: 'price_export', object: 'price' } }], + }, }); // With no invoices the export breaks (Linear JOIN-167, tested below). await seedFakeStripe('invoices', { @@ -140,13 +143,17 @@ test.describe('Stripe', () => { settings.page.waitForEvent('download'), settings.page.getByRole('link', { name: 'Download Subscriptions' }).click(), ]); - const csv = readFileSync((await download.path()) as string, 'utf8').trim().split('\n'); + const csv = readFileSync((await download.path()) as string, 'utf8') + .trim() + .split('\n'); expect(csv[0]).toBe( '"Email","Customer ID","Subscription ID","Subscription Status","Subscription Created","Subscription End","Price ID","Price Name","First Payment","Last Payment"', ); expect(csv[1]).toMatch(/^"exported@example.org","cus_export","sub_export","active",/); - expect(csv[1]).toContain('"price_export","Membership: Standard - GBP 5.00","2026-01-02 00:00:00","2026-01-02 00:00:00"'); + expect(csv[1]).toContain( + '"price_export","Membership: Standard - GBP 5.00","2026-01-02 00:00:00","2026-01-02 00:00:00"', + ); // The plugin reads Stripe with the secret key set on this tab. const [first] = await fakeApiRequests('api.stripe.com'); @@ -175,7 +182,9 @@ test.describe('Stripe', () => { settings.page.waitForEvent('download'), settings.page.getByRole('link', { name: 'Download Subscriptions' }).click(), ]); - const csv = readFileSync((await download.path()) as string, 'utf8').trim().split('\n'); + const csv = readFileSync((await download.path()) as string, 'utf8') + .trim() + .split('\n'); expect(csv[0]).toMatch(/^"Email",/); expect(csv[1]).toMatch(/^"exported@example.org","cus_export","sub_export",/); }); @@ -283,7 +292,15 @@ test.describe('Chargebee', () => { host: 'e2e.chargebee.com', method: 'POST', path: '/hosted_pages/checkout_new_for_items$', - body: { hosted_page: { id: 'hp_e2e', type: 'checkout_new', url: hostedPageUrl, state: 'created', object: 'hosted_page' } }, + body: { + hosted_page: { + id: 'hp_e2e', + type: 'checkout_new', + url: hostedPageUrl, + state: 'created', + object: 'hosted_page', + }, + }, }); await page.route('https://e2e.chargebee.example/**', (route) => route.fulfill({ contentType: 'text/html', body: '

Chargebee

' }), @@ -353,7 +370,10 @@ test.describe('Postcode address lookup', () => { postcode_address_provider: 'get_address_io', get_address_io_api_key: 'e2e-getaddress-key', }); - expect(await joinFormEnv(page)).toMatchObject({ USE_POSTCODE_LOOKUP: true, POSTCODE_ADDRESS_PROVIDER: 'get_address_io' }); + expect(await joinFormEnv(page)).toMatchObject({ + USE_POSTCODE_LOOKUP: true, + POSTCODE_ADDRESS_PROVIDER: 'get_address_io', + }); await overrideFakeApi({ host: 'api.getaddress.io', @@ -387,13 +407,25 @@ test.describe('Postcode address lookup', () => { postcode_address_provider: 'ideal_postcodes', ideal_postcodes_api_key: 'e2e-ideal-key', }); - expect(await joinFormEnv(page)).toMatchObject({ USE_POSTCODE_LOOKUP: true, POSTCODE_ADDRESS_PROVIDER: 'ideal_postcodes' }); + expect(await joinFormEnv(page)).toMatchObject({ + USE_POSTCODE_LOOKUP: true, + POSTCODE_ADDRESS_PROVIDER: 'ideal_postcodes', + }); await overrideFakeApi({ host: 'api.ideal-postcodes.co.uk', path: '^/v1/postcodes/', body: { - result: [{ line_1: '2 Ideal Street', line_2: '', post_town: 'Oxford', county: 'Oxfordshire', postcode: 'OX1 4PE', country: 'England' }], + result: [ + { + line_1: '2 Ideal Street', + line_2: '', + post_town: 'Oxford', + county: 'Oxfordshire', + postcode: 'OX1 4PE', + country: 'England', + }, + ], }, }); diff --git a/packages/join-e2e/tests/settings/logging-debug.spec.ts b/packages/join-e2e/tests/settings/logging-debug.spec.ts index f7c09e1a..6bbcec02 100644 --- a/packages/join-e2e/tests/settings/logging-debug.spec.ts +++ b/packages/join-e2e/tests/settings/logging-debug.spec.ts @@ -1,5 +1,14 @@ import { APIRequestContext } from '@playwright/test'; -import { STANDARD_JOIN_PAGE, expect, getSettings, joinFormEnv, loadLegacySettings, openJoinForm, test, wpEvalJson } from './fixtures'; +import { + STANDARD_JOIN_PAGE, + expect, + getSettings, + joinFormEnv, + loadLegacySettings, + openJoinForm, + test, + wpEvalJson, +} from './fixtures'; /** * Settings page, Logging and Debug tabs. @@ -98,7 +107,9 @@ test.describe('Logging', () => { test('the tab shows the latest log', async ({ settings, request }) => { // A join on a plan that doesn't exist logs the plan's ID. const plan = `log-viewer-${Date.now()}`; - const response = await request.post('/wp-json/join/v1/join', { data: { email: 'someone@example.com', membership: plan } }); + const response = await request.post('/wp-json/join/v1/join', { + data: { email: 'someone@example.com', membership: plan }, + }); expect(response.status()).toBe(500); await settings.open('Logging'); diff --git a/packages/join-e2e/tests/settings/membership-plans.spec.ts b/packages/join-e2e/tests/settings/membership-plans.spec.ts index 0511e2ef..548ab4ee 100644 --- a/packages/join-e2e/tests/settings/membership-plans.spec.ts +++ b/packages/join-e2e/tests/settings/membership-plans.spec.ts @@ -37,7 +37,9 @@ const MEMBER_TAGS_PATH = '/3.0/lists/e2e-audience/members/adf3c55fec42518eefba59 /** A plan as stored under its ID (ck_join_flow_membership_plan_), or false. */ const storedPlan = (id: string) => - wpEvalJson | false>(`return get_option(${JSON.stringify(`ck_join_flow_membership_plan_${id}`)});`); + wpEvalJson | false>( + `return get_option(${JSON.stringify(`ck_join_flow_membership_plan_${id}`)});`, + ); /** The plans the join form on GLOBAL_PLANS_PAGE is given. */ const formPlans = async (page: Page) => (await joinFormEnv(page, GLOBAL_PLANS_PAGE)).MEMBERSHIP_PLANS; @@ -57,7 +59,9 @@ const planPanel = (page: Page, label: string) => async function mailchimpTagChanges(): Promise { return (await fakeApiRequests(MAILCHIMP)) .filter((request) => request.method === 'POST' && request.path === MEMBER_TAGS_PATH) - .flatMap((request) => request.body.tags.map((tag: { name: string; status: string }) => `${tag.name}: ${tag.status}`)); + .flatMap((request) => + request.body.tags.map((tag: { name: string; status: string }) => `${tag.name}: ${tag.status}`), + ); } test.describe('Global membership plans', () => { @@ -117,7 +121,7 @@ test.describe('Global membership plans', () => { }); test.describe('Membership plan fields', () => { - test('Price Point ID becomes the plan\'s ID', async ({ settings, page, request }) => { + test("Price Point ID becomes the plan's ID", async ({ settings, page, request }) => { await settings.open('Membership Plans'); await settings.addPlan({ name: 'Gold', id: 'gold-tier', price: '20' }); await settings.save(); @@ -167,8 +171,12 @@ test.describe('Membership plan fields', () => { await expect(page.locator(CONTINUE)).toHaveText('Continue and pay £15 monthly'); // The plugin enforces the minimum too, not just the form. - expect((await postJoin(request, { membership: 'baseline-plan_monthly_gbp', customMembershipAmount: 5 })).status()).toBe(500); - expect((await postJoin(request, { membership: 'baseline-plan_monthly_gbp', customMembershipAmount: 15 })).ok()).toBe(true); + expect( + (await postJoin(request, { membership: 'baseline-plan_monthly_gbp', customMembershipAmount: 5 })).status(), + ).toBe(500); + expect( + (await postJoin(request, { membership: 'baseline-plan_monthly_gbp', customMembershipAmount: 15 })).ok(), + ).toBe(true); }); test('without it, the price is fixed', async ({ page }) => { @@ -258,7 +266,10 @@ test.describe('Global plans in Stripe', () => { const prices = created.filter((request) => request.path === '/v1/prices').map((request) => request.body); expect(products).toEqual([ - expect.objectContaining({ name: 'Membership: Baseline Plan', metadata: { membership_plan: 'baseline-plan_weekly_gbp' } }), + expect.objectContaining({ + name: 'Membership: Baseline Plan', + metadata: { membership_plan: 'baseline-plan_weekly_gbp' }, + }), expect.objectContaining({ name: 'Membership: Dollars', description: 'Paid in dollars', @@ -335,7 +346,13 @@ test.describe('Member tags', () => { } const subscriptionDeleted = (reason: string) => ({ - object: { id: 'sub_old', object: 'subscription', customer: CUSTOMER.id, status: 'canceled', cancellation_details: { reason } }, + object: { + id: 'sub_old', + object: 'subscription', + customer: CUSTOMER.id, + status: 'canceled', + cancellation_details: { reason }, + }, }); test('have defaults', () => { @@ -346,7 +363,7 @@ test.describe('Member tags', () => { }); }); - test('joining adds the plan\'s Add Tags, and takes off the other plans\' tags and the lapsed, cancelled and lapsing tags', async ({ + test("joining adds the plan's Add Tags, and takes off the other plans' tags and the lapsed, cancelled and lapsing tags", async ({ settings, request, }) => { @@ -427,7 +444,7 @@ test.describe('Member tags', () => { expect(await mailchimpTagChanges()).toEqual(['Left: inactive', 'Payment trouble: inactive']); }); - test('moving to another plan in Stripe swaps the old plan\'s Add Tags for the new one\'s', async ({ + test("moving to another plan in Stripe swaps the old plan's Add Tags for the new one's", async ({ settings, request, }) => { diff --git a/packages/join-e2e/tests/settings/theme.spec.ts b/packages/join-e2e/tests/settings/theme.spec.ts index 1b34b07b..d6ae9fda 100644 --- a/packages/join-e2e/tests/settings/theme.spec.ts +++ b/packages/join-e2e/tests/settings/theme.spec.ts @@ -15,7 +15,10 @@ const cssVariable = (page: Page, name: string) => /** A computed style property of the first element matching `selector`. */ const computed = (page: Page, selector: string, property: string) => - page.locator(selector).first().evaluate((element, name) => getComputedStyle(element).getPropertyValue(name), property); + page + .locator(selector) + .first() + .evaluate((element, name) => getComputedStyle(element).getPropertyValue(name), property); test('the colours have defaults before anything is saved', async ({ page }) => { expect(getSettings(['theme_primary_color', 'theme_gray_color', 'theme_background_color'])).toEqual({ @@ -30,7 +33,7 @@ test('the colours have defaults before anything is saved', async ({ page }) => { expect(await cssVariable(page, '--ck-join-form-background-color')).toBe('#f4f1ee'); }); -test('Primary Color colours the form\'s buttons', async ({ settings, page }) => { +test("Primary Color colours the form's buttons", async ({ settings, page }) => { await settings.open('Theme'); await settings.setColor('Primary Color', '#336699'); await settings.save(); @@ -42,7 +45,7 @@ test('Primary Color colours the form\'s buttons', async ({ settings, page }) => expect(await computed(page, CONTINUE, 'background-color')).toBe('rgb(51, 102, 153)'); }); -test('Gray Color and Background Color reach the form\'s styles', async ({ settings, page }) => { +test("Gray Color and Background Color reach the form's styles", async ({ settings, page }) => { await settings.open('Theme'); await settings.setColor('Gray Color', '#aabbcc'); await settings.setColor('Background Color', '#fafafa'); @@ -57,7 +60,7 @@ test('Gray Color and Background Color reach the form\'s styles', async ({ settin expect((await cssVariable(page, '--ck-join-form-background-color')).toLowerCase()).toBe('#fafafa'); }); -test('Custom Css is added to the join form\'s page', async ({ settings, page }) => { +test("Custom Css is added to the join form's page", async ({ settings, page }) => { const css = '.ck-join-flow { outline: 3px solid rgb(255, 0, 0); }'; await settings.open('Theme'); await settings.setText('Custom Css', css); diff --git a/packages/join-e2e/tests/supporter-mode-edge-cases.spec.ts b/packages/join-e2e/tests/supporter-mode-edge-cases.spec.ts index 2ffd506f..745ddd5b 100644 --- a/packages/join-e2e/tests/supporter-mode-edge-cases.spec.ts +++ b/packages/join-e2e/tests/supporter-mode-edge-cases.spec.ts @@ -52,9 +52,7 @@ test.describe('One-off tab disabled when STRIPE_DIRECT_DEBIT_ONLY=true', () => { }); test('explanatory note about Direct Debit is shown', async ({ page }) => { - await expect( - page.locator('p:has-text("One-off donations are not available with Direct Debit")'), - ).toBeVisible(); + await expect(page.locator('p:has-text("One-off donations are not available with Direct Debit")')).toBeVisible(); }); test('Monthly tab still works and advances the form', async ({ page }) => { @@ -79,9 +77,7 @@ test.describe('No plans configured warning', () => { }); test('"No donation amounts configured" warning is shown', async ({ page }) => { - await expect( - page.locator('[role="alert"]:has-text("No donation amounts configured")'), - ).toBeVisible(); + await expect(page.locator('[role="alert"]:has-text("No donation amounts configured")')).toBeVisible(); }); test('no tier buttons or frequency toggle are rendered', async ({ page }) => { diff --git a/packages/join-e2e/tsconfig.json b/packages/join-e2e/tsconfig.json new file mode 100644 index 00000000..bc2abaca --- /dev/null +++ b/packages/join-e2e/tsconfig.json @@ -0,0 +1,15 @@ +{ + "compilerOptions": { + "target": "es2022", + "lib": ["es2022", "dom"], + "module": "commonjs", + "moduleResolution": "node", + "strict": true, + "noEmit": true, + "skipLibCheck": true, + "esModuleInterop": true, + "forceConsistentCasingInFileNames": true, + "types": ["node"] + }, + "include": ["tests", "playwright.config.ts"] +} diff --git a/readme.md b/readme.md index 73b59a6c..caab20fe 100644 --- a/readme.md +++ b/readme.md @@ -436,14 +436,17 @@ cd packages/join-flow npm test ``` -### Frontend formatting +### Formatting and type checks -CI fails if `packages/join-flow` isn't formatted with Prettier. To fix formatting, from the repository root: +CI fails if `packages/join-flow` or `packages/join-e2e` isn't formatted with Prettier, or if either doesn't type-check (the join form, its Jest tests, and the E2E tests). From the repository root: ```bash -npm run prettier +npm run prettier # fix formatting +npm run typecheck # type check both packages ``` +`packages/join-e2e` has its own Prettier settings (`packages/join-e2e/.prettierrc.json`), matching how its tests were already written. + ### Backend unit tests ```bash @@ -453,7 +456,7 @@ cd packages/join-block ### Backend linting -CI runs phpcs and PHPStan on `packages/join-block` and fails on any phpcs error or PHPStan error. Run both locally with: +CI runs phpcs and PHPStan on `packages/join-block`, its PHPUnit tests included, and fails on any phpcs error or PHPStan error. Run both locally with: ```bash cd packages/join-block From c96c51849862c43399f05c92dddd7168a13afe29 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 24 Oct 2026 19:52:18 +0000 Subject: [PATCH 2/6] Address review findings on the type checks - Remove the CamelCaps phpcs:ignore comments in tests, which phpcs.xml now excludes for tests anyway. - Mock wpdb by class, so the @var matches the real type. - CI type check: skip the root postinstall (Composer), and run the root typecheck script rather than repeating its steps. - Type-check the fake API (with a looser config, so plain JS needs no annotations), and pin @types/node to 20 to match CI's Node. - Readme: the type check needs the E2E dependencies installed. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BL2bFrTk84JMy3CPAsCTV9 --- .github/workflows/jest-tests.yml | 23 ++++++++----------- .../tests/JoinServiceFreeMembershipTest.php | 3 --- .../tests/JoinServiceMailchimpTest.php | 3 --- .../join-block/tests/LapsingFilterTest.php | 3 --- .../tests/MailchimpServiceLegacyTagsTest.php | 3 --- .../tests/MailchimpServiceTagsTest.php | 3 --- .../tests/SettingsComputeTagsToRemoveTest.php | 2 -- .../SettingsMembershipPlanLookupTest.php | 2 +- .../tests/StripeInvoicePaidTest.php | 3 --- .../tests/ZetkinServiceTagsTest.php | 3 --- packages/join-e2e/fake-api/server.js | 15 ++++++++++-- packages/join-e2e/fake-api/tsconfig.json | 10 ++++++++ packages/join-e2e/package-lock.json | 8 +++---- packages/join-e2e/package.json | 4 ++-- readme.md | 3 ++- 15 files changed, 42 insertions(+), 46 deletions(-) create mode 100644 packages/join-e2e/fake-api/tsconfig.json diff --git a/.github/workflows/jest-tests.yml b/.github/workflows/jest-tests.yml index 57cbb05e..0dbdb1d1 100644 --- a/.github/workflows/jest-tests.yml +++ b/.github/workflows/jest-tests.yml @@ -53,18 +53,15 @@ jobs: with: node-version: '20' - # The postinstall installs join-flow's dependencies, which its type - # check needs. - - name: Install root deps - run: npm ci - - - name: Type check the join form and its Jest tests - run: npx tsc --noEmit -p packages/join-flow - - - name: Install E2E deps - working-directory: packages/join-e2e - run: npm ci + # TypeScript, plus each package's dependencies. The root postinstall + # also runs Composer, which the type check doesn't need, so it's + # skipped and join-flow's dependencies are installed directly. + - name: Install dependencies + run: | + npm ci --ignore-scripts + npm --prefix packages/join-flow ci + npm --prefix packages/join-e2e ci - - name: Type check the E2E tests - working-directory: packages/join-e2e + # The join form and its Jest tests, the E2E tests and the fake API. + - name: Type check run: npm run typecheck diff --git a/packages/join-block/tests/JoinServiceFreeMembershipTest.php b/packages/join-block/tests/JoinServiceFreeMembershipTest.php index 2dc0d2da..30f6e7d8 100644 --- a/packages/join-block/tests/JoinServiceFreeMembershipTest.php +++ b/packages/join-block/tests/JoinServiceFreeMembershipTest.php @@ -147,17 +147,14 @@ public function get_results(string $query, $output = null): array $joinBlockLog = new class { public array $errors = []; - // phpcs:ignore PSR1.Methods.CamelCapsMethodName.NotCamelCaps public function info(string $msg, array $ctx = []): void { } - // phpcs:ignore PSR1.Methods.CamelCapsMethodName.NotCamelCaps public function warning(string $msg, array $ctx = []): void { } - // phpcs:ignore PSR1.Methods.CamelCapsMethodName.NotCamelCaps public function error(string $msg, array $ctx = []): void { $this->errors[] = $msg; diff --git a/packages/join-block/tests/JoinServiceMailchimpTest.php b/packages/join-block/tests/JoinServiceMailchimpTest.php index ce014417..586996fc 100644 --- a/packages/join-block/tests/JoinServiceMailchimpTest.php +++ b/packages/join-block/tests/JoinServiceMailchimpTest.php @@ -121,17 +121,14 @@ public function get_results(string $query, $output = null): array $joinBlockLog = new class { public array $errors = []; - // phpcs:ignore PSR1.Methods.CamelCapsMethodName.NotCamelCaps public function info(string $msg, array $ctx = []): void { } - // phpcs:ignore PSR1.Methods.CamelCapsMethodName.NotCamelCaps public function warning(string $msg, array $ctx = []): void { } - // phpcs:ignore PSR1.Methods.CamelCapsMethodName.NotCamelCaps public function error(string $msg, array $ctx = []): void { $this->errors[] = $msg; diff --git a/packages/join-block/tests/LapsingFilterTest.php b/packages/join-block/tests/LapsingFilterTest.php index 9315db62..6ca828e0 100644 --- a/packages/join-block/tests/LapsingFilterTest.php +++ b/packages/join-block/tests/LapsingFilterTest.php @@ -23,15 +23,12 @@ protected function setUp(): void global $joinBlockLog; $joinBlockLog = new class { - // phpcs:ignore PSR1.Methods.CamelCapsMethodName.NotCamelCaps public function info($msg, $ctx = []) { } - // phpcs:ignore PSR1.Methods.CamelCapsMethodName.NotCamelCaps public function warning($msg, $ctx = []) { } - // phpcs:ignore PSR1.Methods.CamelCapsMethodName.NotCamelCaps public function error($msg, $ctx = []) { } diff --git a/packages/join-block/tests/MailchimpServiceLegacyTagsTest.php b/packages/join-block/tests/MailchimpServiceLegacyTagsTest.php index be8fe964..162aa322 100644 --- a/packages/join-block/tests/MailchimpServiceLegacyTagsTest.php +++ b/packages/join-block/tests/MailchimpServiceLegacyTagsTest.php @@ -40,19 +40,16 @@ protected function setUp(): void public array $warnings = []; public array $errors = []; - // phpcs:ignore PSR1.Methods.CamelCapsMethodName.NotCamelCaps public function info(string $msg, array $ctx = []): void { $this->infos[] = $msg; } - // phpcs:ignore PSR1.Methods.CamelCapsMethodName.NotCamelCaps public function warning(string $msg, array $ctx = []): void { $this->warnings[] = $msg; } - // phpcs:ignore PSR1.Methods.CamelCapsMethodName.NotCamelCaps public function error(string $msg, array $ctx = []): void { $this->errors[] = $msg; diff --git a/packages/join-block/tests/MailchimpServiceTagsTest.php b/packages/join-block/tests/MailchimpServiceTagsTest.php index 1fdfc036..262cc20a 100644 --- a/packages/join-block/tests/MailchimpServiceTagsTest.php +++ b/packages/join-block/tests/MailchimpServiceTagsTest.php @@ -38,17 +38,14 @@ protected function setUp(): void $joinBlockLog = new class { public array $errors = []; - // phpcs:ignore PSR1.Methods.CamelCapsMethodName.NotCamelCaps public function info(string $msg, array $ctx = []): void { } - // phpcs:ignore PSR1.Methods.CamelCapsMethodName.NotCamelCaps public function warning(string $msg, array $ctx = []): void { } - // phpcs:ignore PSR1.Methods.CamelCapsMethodName.NotCamelCaps public function error(string $msg, array $ctx = []): void { $this->errors[] = $msg; diff --git a/packages/join-block/tests/SettingsComputeTagsToRemoveTest.php b/packages/join-block/tests/SettingsComputeTagsToRemoveTest.php index 519b6002..2a5dfa62 100644 --- a/packages/join-block/tests/SettingsComputeTagsToRemoveTest.php +++ b/packages/join-block/tests/SettingsComputeTagsToRemoveTest.php @@ -46,12 +46,10 @@ public function prepare(string $query, ...$args): string { return $query; } - // phpcs:ignore PSR1.Methods.CamelCapsMethodName.NotCamelCaps public function esc_like(string $text): string { return $text; } - // phpcs:ignore PSR1.Methods.CamelCapsMethodName.NotCamelCaps public function get_results(string $query, $output = null): array { return $this->rows; diff --git a/packages/join-block/tests/SettingsMembershipPlanLookupTest.php b/packages/join-block/tests/SettingsMembershipPlanLookupTest.php index e32b1851..0b0c8fe5 100644 --- a/packages/join-block/tests/SettingsMembershipPlanLookupTest.php +++ b/packages/join-block/tests/SettingsMembershipPlanLookupTest.php @@ -161,7 +161,7 @@ private function stubWpdbWithRows(array $rows): void { global $wpdb; /** @var \wpdb&\Mockery\MockInterface $wpdb */ - $wpdb = Mockery::mock(); + $wpdb = Mockery::mock(\wpdb::class); $wpdb->options = 'wp_options'; $wpdb->shouldReceive('esc_like')->andReturnUsing(fn($s) => $s); $wpdb->shouldReceive('prepare')->andReturnUsing(fn($sql) => $sql); diff --git a/packages/join-block/tests/StripeInvoicePaidTest.php b/packages/join-block/tests/StripeInvoicePaidTest.php index e868ecb5..8b0a95a9 100644 --- a/packages/join-block/tests/StripeInvoicePaidTest.php +++ b/packages/join-block/tests/StripeInvoicePaidTest.php @@ -32,17 +32,14 @@ protected function setUp(): void $joinBlockLog = new class { public array $errors = []; - // phpcs:ignore PSR1.Methods.CamelCapsMethodName.NotCamelCaps public function info(string $msg, array $ctx = []): void { } - // phpcs:ignore PSR1.Methods.CamelCapsMethodName.NotCamelCaps public function warning(string $msg, array $ctx = []): void { } - // phpcs:ignore PSR1.Methods.CamelCapsMethodName.NotCamelCaps public function error(string $msg, array $ctx = []): void { $this->errors[] = $msg; diff --git a/packages/join-block/tests/ZetkinServiceTagsTest.php b/packages/join-block/tests/ZetkinServiceTagsTest.php index 295b0986..15dabd69 100644 --- a/packages/join-block/tests/ZetkinServiceTagsTest.php +++ b/packages/join-block/tests/ZetkinServiceTagsTest.php @@ -34,19 +34,16 @@ protected function setUp(): void public array $warnings = []; public array $errors = []; - // phpcs:ignore PSR1.Methods.CamelCapsMethodName.NotCamelCaps public function info(string $msg, array $ctx = []): void { $this->infos[] = $msg; } - // phpcs:ignore PSR1.Methods.CamelCapsMethodName.NotCamelCaps public function warning(string $msg, array $ctx = []): void { $this->warnings[] = $msg; } - // phpcs:ignore PSR1.Methods.CamelCapsMethodName.NotCamelCaps public function error(string $msg, array $ctx = []): void { $this->errors[] = $msg; diff --git a/packages/join-e2e/fake-api/server.js b/packages/join-e2e/fake-api/server.js index f895a3fb..91929d25 100644 --- a/packages/join-e2e/fake-api/server.js +++ b/packages/join-e2e/fake-api/server.js @@ -27,6 +27,7 @@ function freshStripe() { return { counter: 0, objects: { products: [], prices: [], customers: [], subscriptions: [], invoices: [] } }; } +/** @returns {{ counter: number, tags: { id: number, title: string }[] }} */ function freshZetkin() { return { counter: 0, tags: [] }; } @@ -191,12 +192,17 @@ function respond(host, method, url, body) { return { status: 200, body: {} }; } +/** + * @param {import('http').IncomingMessage} request + * @param {import('http').ServerResponse} response + */ function handleService(request, response) { + /** @type {Buffer[]} */ const chunks = []; request.on('data', (chunk) => chunks.push(chunk)); request.on('end', () => { const host = (request.headers.host || '').split(':')[0]; - const url = new URL(request.url, `https://${host}`); + const url = new URL(request.url || '/', `https://${host}`); let buffer = Buffer.concat(chunks); // Sentry, for one, gzips what it sends. A body that won't unzip is // recorded as it came, rather than crashing the fake. @@ -224,7 +230,12 @@ function handleService(request, response) { }); } +/** + * @param {import('http').IncomingMessage} request + * @param {import('http').ServerResponse} response + */ function handleControl(request, response) { + /** @type {Buffer[]} */ const chunks = []; request.on('data', (chunk) => chunks.push(chunk)); request.on('end', () => { @@ -263,7 +274,7 @@ function handleControl(request, response) { } // Puts an object straight into the fake Stripe, e.g. POST /stripe/customers // with {"id": "cus_1", "email": "..."}, for tests that need one to exist. - const stripeSeed = request.url.match(/^\/stripe\/([a-z_]+)$/); + const stripeSeed = (request.url || '').match(/^\/stripe\/([a-z_]+)$/); if (request.method === 'POST' && stripeSeed && stripe.objects[stripeSeed[1]]) { const object = JSON.parse(Buffer.concat(chunks).toString('utf8')); stripe.objects[stripeSeed[1]].push(object); diff --git a/packages/join-e2e/fake-api/tsconfig.json b/packages/join-e2e/fake-api/tsconfig.json new file mode 100644 index 00000000..2e1d290d --- /dev/null +++ b/packages/join-e2e/fake-api/tsconfig.json @@ -0,0 +1,10 @@ +{ + "extends": "../tsconfig.json", + "compilerOptions": { + "allowJs": true, + "checkJs": true, + "noImplicitAny": false, + "useUnknownInCatchVariables": false + }, + "include": ["."] +} diff --git a/packages/join-e2e/package-lock.json b/packages/join-e2e/package-lock.json index e2c78ab5..098636b3 100644 --- a/packages/join-e2e/package-lock.json +++ b/packages/join-e2e/package-lock.json @@ -9,7 +9,7 @@ "version": "1.0.0", "devDependencies": { "@playwright/test": "^1.63.0", - "@types/node": "^22.20.5", + "@types/node": "^20.19.0", "typescript": "^5.9.3" } }, @@ -30,9 +30,9 @@ } }, "node_modules/@types/node": { - "version": "22.20.5", - "resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.5.tgz", - "integrity": "sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA==", + "version": "20.19.43", + "resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.43.tgz", + "integrity": "sha512-6oYBAi5ikg4Pl+kGsoYtawUMBT2zZMCvPNF7pVLnHZfd1zf38DRiWn/gT01RYCdUqkv7Fhr+C9ot4/tb+2sVvA==", "dev": true, "license": "MIT", "dependencies": { diff --git a/packages/join-e2e/package.json b/packages/join-e2e/package.json index ba3aabc8..148dbe3c 100644 --- a/packages/join-e2e/package.json +++ b/packages/join-e2e/package.json @@ -9,11 +9,11 @@ "env:stop": "bash scripts/env.sh stop", "env:destroy": "bash scripts/env.sh destroy", "pretest": "bash scripts/seed.sh", - "typecheck": "tsc --noEmit -p ." + "typecheck": "tsc --noEmit -p . && tsc --noEmit -p fake-api" }, "devDependencies": { "@playwright/test": "^1.63.0", - "@types/node": "^22.20.5", + "@types/node": "^20.19.0", "typescript": "^5.9.3" } } diff --git a/readme.md b/readme.md index cfe8a37a..f3095f2e 100644 --- a/readme.md +++ b/readme.md @@ -438,9 +438,10 @@ npm test ### Formatting and type checks -CI fails if `packages/join-flow` or `packages/join-e2e` isn't formatted with Prettier, or if either doesn't type-check (the join form, its Jest tests, and the E2E tests). From the repository root: +CI fails if `packages/join-flow` or `packages/join-e2e` isn't formatted with Prettier, or if either doesn't type-check (the join form, its Jest tests, the E2E tests and the E2E suite's fake API). The type check needs the E2E dependencies, which `npm install` at the root doesn't install. From the repository root: ```bash +npm --prefix packages/join-e2e ci # once npm run prettier # fix formatting npm run typecheck # type check both packages ``` From 577ff17acea7a96d2b796e29b6d4640a85d04f9c Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 18:28:31 +0000 Subject: [PATCH 3/6] Type the plan page's form, so the join form type-checks The income guidance table (#125) added the plan page's first setValue calls. The page's useForm had no type, so TypeScript allowed no field names at all, and the type check this PR adds failed. Give it FormSchema, as the donation page does. Types only; nothing changes at runtime. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BL2bFrTk84JMy3CPAsCTV9 --- packages/join-flow/src/pages/plan.page.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/join-flow/src/pages/plan.page.tsx b/packages/join-flow/src/pages/plan.page.tsx index 604e10f6..48f3180a 100644 --- a/packages/join-flow/src/pages/plan.page.tsx +++ b/packages/join-flow/src/pages/plan.page.tsx @@ -25,7 +25,7 @@ export const PlanPage: StagerComponent = ({ data, onCompleted }) => { - const form = useForm({ + const form = useForm({ defaultValues: data as {} }); From 04dcdf03cdb504a5ce7a288af399de54f95f25d9 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 12 Nov 2026 11:48:44 +0000 Subject: [PATCH 4/6] Bring master's new Stripe price test up to the test lint rules StripePriceReuseTest (from #146) arrived with the merge of master. With phpcs and PHPStan now covering the tests: - Put the log stub's empty method bodies on their own lines (phpcbf). - Drop its CamelCaps phpcs:ignore comments; phpcs.xml excludes that rule for tests. - Reset Stripe's HTTP client to its default CurlClient rather than null, which the SDK's signature doesn't allow, as StripeInvoicePaidTest does. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BL2bFrTk84JMy3CPAsCTV9 --- .../join-block/tests/StripePriceReuseTest.php | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/packages/join-block/tests/StripePriceReuseTest.php b/packages/join-block/tests/StripePriceReuseTest.php index c9f326fe..d96245a0 100644 --- a/packages/join-block/tests/StripePriceReuseTest.php +++ b/packages/join-block/tests/StripePriceReuseTest.php @@ -54,14 +54,17 @@ protected function setUp(): void global $joinBlockLog; $joinBlockLog = new class { - // phpcs:ignore PSR1.Methods.CamelCapsMethodName.NotCamelCaps - public function info(string $msg, array $ctx = []): void {} + public function info(string $msg, array $ctx = []): void + { + } - // phpcs:ignore PSR1.Methods.CamelCapsMethodName.NotCamelCaps - public function warning(string $msg, array $ctx = []): void {} + public function warning(string $msg, array $ctx = []): void + { + } - // phpcs:ignore PSR1.Methods.CamelCapsMethodName.NotCamelCaps - public function error(string $msg, array $ctx = []): void {} + public function error(string $msg, array $ctx = []): void + { + } }; \Stripe\Stripe::setApiKey('sk_test_fake'); @@ -73,7 +76,7 @@ protected function tearDown(): void { global $joinBlockLog; $joinBlockLog = null; - \Stripe\ApiRequestor::setHttpClient(null); + \Stripe\ApiRequestor::setHttpClient(\Stripe\HttpClient\CurlClient::instance()); Monkey\tearDown(); parent::tearDown(); } From 12576aaed540be218e2f1ef3a64da0d72a25ab96 Mon Sep 17 00:00:00 2001 From: Joaquim de Souza Date: Thu, 12 Nov 2026 12:01:02 +0000 Subject: [PATCH 5/6] Read the lock test process's argument from $_SERVER['argv'] PHPStan now covers the tests and reports that $argv might not be defined at file scope. Co-Authored-By: Claude Opus 5.5 --- packages/join-block/tests/SessionLockTestProcess.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/join-block/tests/SessionLockTestProcess.php b/packages/join-block/tests/SessionLockTestProcess.php index 9ee5e192..f5641c09 100644 --- a/packages/join-block/tests/SessionLockTestProcess.php +++ b/packages/join-block/tests/SessionLockTestProcess.php @@ -28,7 +28,7 @@ $joinBlockLogFile = fopen($joinBlockLogLocation, 'a'); $joinBlockLog->pushHandler(new StreamHandler($joinBlockLogFile, Level::Info)); -$lockKey = $argv[1]; +$lockKey = $_SERVER['argv'][1]; $joinBlockLog->info("Testing lock with key $lockKey"); From 6e06419f21c0c7e233c53e0f7241059bb5fbf242 Mon Sep 17 00:00:00 2001 From: Joaquim de Souza Date: Thu, 12 Nov 2026 12:07:59 +0000 Subject: [PATCH 6/6] Address code review on the test suite checks - Type-check the fake API strictly: JSDoc types for its requests, overrides and Stripe store, instead of turning off noImplicitAny and useUnknownInCatchVariables. A Stripe seed with bad JSON now gets a 400 rather than crashing the fake. - Stub $wpdb in SettingsMembershipPlanLookupTest with a plain class, as the other tests do. A Mockery double of \wpdb declared an empty global wpdb class, as WordPress isn't loaded in unit tests. - Merge the two CamelCapsMethodName rules in phpcs.xml into one. - Run the type check in the Jest job, which already installs join-flow's dependencies, instead of a separate job with its own install. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/jest-tests.yml | 33 +++----- packages/join-block/phpcs.xml | 10 +-- .../SettingsMembershipPlanLookupTest.php | 31 ++++++-- packages/join-e2e/fake-api/server.js | 77 +++++++++++++++++-- packages/join-e2e/fake-api/tsconfig.json | 4 +- 5 files changed, 109 insertions(+), 46 deletions(-) diff --git a/.github/workflows/jest-tests.yml b/.github/workflows/jest-tests.yml index 0dbdb1d1..b22bcd63 100644 --- a/.github/workflows/jest-tests.yml +++ b/.github/workflows/jest-tests.yml @@ -9,7 +9,7 @@ on: jobs: jest-tests: - name: Jest tests + name: Jest tests and type check runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 @@ -25,6 +25,15 @@ jobs: working-directory: packages/join-flow run: npm test + # The type check reuses this job's install of join-flow's dependencies + # (from the root postinstall) and only adds the E2E package's. + - name: Install E2E deps + run: npm --prefix packages/join-e2e ci + + # The join form and its Jest tests, the E2E tests and the fake API. + - name: Type check + run: npm run typecheck + prettier: name: Prettier runs-on: ubuntu-latest @@ -43,25 +52,3 @@ jobs: - name: Check formatting run: npx prettier --check packages/join-flow packages/join-e2e - typecheck: - name: Type check - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - - uses: actions/setup-node@v4 - with: - node-version: '20' - - # TypeScript, plus each package's dependencies. The root postinstall - # also runs Composer, which the type check doesn't need, so it's - # skipped and join-flow's dependencies are installed directly. - - name: Install dependencies - run: | - npm ci --ignore-scripts - npm --prefix packages/join-flow ci - npm --prefix packages/join-e2e ci - - # The join form and its Jest tests, the E2E tests and the fake API. - - name: Type check - run: npm run typecheck diff --git a/packages/join-block/phpcs.xml b/packages/join-block/phpcs.xml index dcfb0cea..30183177 100644 --- a/packages/join-block/phpcs.xml +++ b/packages/join-block/phpcs.xml @@ -17,18 +17,16 @@
- - - tests/* - - src/CK_Theme_Options_Container.php + src/CK_Theme_Options_Container.php + tests/* diff --git a/packages/join-block/tests/SettingsMembershipPlanLookupTest.php b/packages/join-block/tests/SettingsMembershipPlanLookupTest.php index 0b0c8fe5..bc4ce9e3 100644 --- a/packages/join-block/tests/SettingsMembershipPlanLookupTest.php +++ b/packages/join-block/tests/SettingsMembershipPlanLookupTest.php @@ -4,7 +4,6 @@ use Brain\Monkey; use CommonKnowledge\JoinBlock\Settings; -use Mockery; use Mockery\Adapter\Phpunit\MockeryPHPUnitIntegration; use PHPUnit\Framework\TestCase; @@ -160,11 +159,29 @@ public function testReturnsFalsyWhenNoStoredPlanMatches(): void private function stubWpdbWithRows(array $rows): void { global $wpdb; - /** @var \wpdb&\Mockery\MockInterface $wpdb */ - $wpdb = Mockery::mock(\wpdb::class); - $wpdb->options = 'wp_options'; - $wpdb->shouldReceive('esc_like')->andReturnUsing(fn($s) => $s); - $wpdb->shouldReceive('prepare')->andReturnUsing(fn($sql) => $sql); - $wpdb->shouldReceive('get_results')->andReturn($rows); + // A plain stub rather than a Mockery double of \wpdb: WordPress isn't + // loaded here, and mocking the class would declare an empty global wpdb. + $wpdb = new class ($rows) { + public string $options = 'wp_options'; + + public function __construct(private array $rows) + { + } + + public function prepare(string $query, ...$args): string + { + return $query; + } + + public function esc_like(string $text): string + { + return $text; + } + + public function get_results(string $query, $output = null): array + { + return $this->rows; + } + }; } } diff --git a/packages/join-e2e/fake-api/server.js b/packages/join-e2e/fake-api/server.js index 6b15d146..70e8d899 100644 --- a/packages/join-e2e/fake-api/server.js +++ b/packages/join-e2e/fake-api/server.js @@ -18,11 +18,30 @@ const path = require('path'); const zlib = require('zlib'); const { URL } = require('url'); +/** + * A request body as the fake parsed it: JSON or Stripe-style form data as an + * object, otherwise the raw text. Any shape can arrive, so it isn't narrowed. + * @typedef {any} Body + */ +/** @typedef {Record} StripeObject An object in the fake Stripe, as JSON. */ +/** @typedef {{ status: number, body: unknown }} FakeResponse */ +/** + * A response override a test set through the control API. + * @typedef {{ host?: string, method?: string, path?: string, pathPattern?: RegExp | null, status?: number, body?: unknown }} Override + */ +/** + * @typedef {{ time: string, host: string, method?: string, path: string, query: Record, + * headers: import('http').IncomingHttpHeaders, body: Body }} RecordedRequest + */ + +/** @type {RecordedRequest[]} */ let requests = []; +/** @type {Override[]} */ let overrides = []; let stripe = freshStripe(); let zetkin = freshZetkin(); +/** @returns {{ counter: number, objects: Record }} */ function freshStripe() { return { counter: 0, objects: { products: [], prices: [], customers: [], subscriptions: [], invoices: [] } }; } @@ -32,6 +51,11 @@ function freshZetkin() { return { counter: 0, tags: [] }; } +/** + * @param {string} raw + * @param {string | undefined} contentType + * @returns {Body} + */ function parseBody(raw, contentType) { if (!raw) return null; if ((contentType || '').includes('application/json')) { @@ -47,8 +71,12 @@ function parseBody(raw, contentType) { return raw; } -/** Stripe-style form encoding, with nested keys like metadata[membership_plan]. */ +/** + * Stripe-style form encoding, with nested keys like metadata[membership_plan]. + * @param {string} raw + */ function parseFormEncoded(raw) { + /** @type {Record} */ const result = {}; for (const [key, value] of new URLSearchParams(raw)) { const parts = key.replace(/\]/g, '').split('['); @@ -70,10 +98,14 @@ function parseFormEncoded(raw) { * sends: plain fields (?customer=cus_1), ranges (?created[gte]=...), and * subscriptions' status, where "all" means any and leaving it out means any * but canceled. + * @param {string} type + * @param {StripeObject[]} store + * @param {URL} url */ function listStripe(type, store, url) { const ignored = ['limit', 'starting_after', 'ending_before']; const params = [...url.searchParams].filter(([key]) => !ignored.includes(key) && !key.startsWith('expand')); + /** @type {Record boolean>} */ const ranges = { gt: (a, b) => a > b, gte: (a, b) => a >= b, lt: (a, b) => a < b, lte: (a, b) => a <= b }; const hasStatus = params.some(([key]) => key === 'status'); return store.filter((object) => { @@ -92,11 +124,16 @@ function listStripe(type, store, url) { * a test seeded it: an id and the fields every object has (seeded objects * can set their own, e.g. an older `created`), amounts as integers and * currencies in lowercase. + * @param {string} type + * @param {Body} fields + * @returns {StripeObject} */ function newStripeObject(type, fields) { - const prefix = - { products: 'prod', prices: 'price', customers: 'cus', subscriptions: 'sub', invoices: 'in' }[type] || type; + /** @type {Record} */ + const prefixes = { products: 'prod', prices: 'price', customers: 'cus', subscriptions: 'sub', invoices: 'in' }; + const prefix = prefixes[type] || type; stripe.counter += 1; + /** @type {StripeObject} */ const object = { id: `${prefix}_e2e_${stripe.counter}`, object: type.replace(/s$/, ''), @@ -114,6 +151,10 @@ function newStripeObject(type, fields) { /** * A tiny in-memory Stripe: enough for the plugin's product and price set-up, * and for the customer and subscription look-ups its webhook handlers make. + * @param {string | undefined} method + * @param {URL} url + * @param {Body} body + * @returns {FakeResponse | null} */ function fakeStripe(method, url, body) { const match = url.pathname.match(/^\/v1\/([a-z_]+)(?:\/([^/]+))?$/); @@ -163,6 +204,10 @@ function fakeStripe(method, url, body) { /** * A tiny in-memory Zetkin (api.zetk.in and api.dev.zetkin.org): enough for * the plugin's OAuth sign-in, adding a person and tagging them. + * @param {string | undefined} method + * @param {URL} url + * @param {Body} body + * @returns {FakeResponse | null} */ function fakeZetkin(method, url, body) { const path = url.pathname.replace(/^\/v1/, ''); @@ -187,6 +232,13 @@ function fakeZetkin(method, url, body) { return null; } +/** + * @param {string} host + * @param {string | undefined} method + * @param {URL} url + * @param {Body} body + * @returns {FakeResponse} + */ function respond(host, method, url, body) { const override = overrides.find( (rule) => @@ -232,7 +284,7 @@ function handleService(request, response) { try { buffer = zlib.gunzipSync(buffer); } catch (error) { - console.error(`Could not gunzip a request to ${host}${request.url}: ${error.message}`); + console.error(`Could not gunzip a request to ${host}${request.url}: ${errorMessage(error)}`); } } const raw = buffer.toString('utf8'); @@ -261,6 +313,10 @@ function handleControl(request, response) { const chunks = []; request.on('data', (chunk) => chunks.push(chunk)); request.on('end', () => { + /** + * @param {number} status + * @param {unknown} body + */ const send = (status, body) => { response.writeHead(status, { 'Content-Type': 'application/json' }); response.end(JSON.stringify(body)); @@ -271,7 +327,7 @@ function handleControl(request, response) { try { return JSON.parse(Buffer.concat(chunks).toString('utf8')); } catch (error) { - send(400, { error: `invalid JSON: ${error.message}` }); + send(400, { error: `invalid JSON: ${errorMessage(error)}` }); return undefined; } }; @@ -289,7 +345,7 @@ function handleControl(request, response) { try { rule.pathPattern = rule.path ? new RegExp(rule.path) : null; } catch (error) { - return send(400, { error: `invalid path pattern: ${error.message}` }); + return send(400, { error: `invalid path pattern: ${errorMessage(error)}` }); } overrides.unshift(rule); return send(200, { ok: true }); @@ -299,7 +355,9 @@ function handleControl(request, response) { // It is stored as Stripe would store it (newStripeObject). const stripeSeed = (request.url || '').match(/^\/stripe\/([a-z_]+)$/); if (request.method === 'POST' && stripeSeed && stripe.objects[stripeSeed[1]]) { - const object = newStripeObject(stripeSeed[1], JSON.parse(Buffer.concat(chunks).toString('utf8'))); + const fields = readJson(); + if (fields === undefined) return; + const object = newStripeObject(stripeSeed[1], fields); stripe.objects[stripeSeed[1]].push(object); return send(200, object); } @@ -308,6 +366,11 @@ function handleControl(request, response) { }); } +/** @param {unknown} error */ +function errorMessage(error) { + return error instanceof Error ? error.message : String(error); +} + const certs = path.join(__dirname, 'certs'); https .createServer( diff --git a/packages/join-e2e/fake-api/tsconfig.json b/packages/join-e2e/fake-api/tsconfig.json index 2e1d290d..3fe3a7d2 100644 --- a/packages/join-e2e/fake-api/tsconfig.json +++ b/packages/join-e2e/fake-api/tsconfig.json @@ -2,9 +2,7 @@ "extends": "../tsconfig.json", "compilerOptions": { "allowJs": true, - "checkJs": true, - "noImplicitAny": false, - "useUnknownInCatchVariables": false + "checkJs": true }, "include": ["."] }