Skip to content

Open-source social media scheduler built for AI agents and the teams behind them. Create, schedule and publish posts to every network through MCP or the REST API, or write them yourself in a composer your team will love.

Move every browser test to the shared wait helpers (#487)

Paulo Castellanob399de4fc79c
diff --git a/AGENTS.md b/AGENTS.md
index 8079aa3d5..30aa3a501 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -1240,11 +1240,14 @@ Browser tests live in `tests/Browser` and run on `pestphp/pest-plugin-browser` d
- `waitFor($page, '@id')`: an element is mounted and laid out.
- `waitForGone($page, '@id')`: no element matches.
- `waitForState($page, '@id', "element.getAttribute('aria-checked') === 'true'")`: an element exists and the expression about `element` is true (attributes, `dataset`, `disabled`, position).
+ - `waitForOpen($page, '@post-composer-dialog')`: a dialog, sheet or popover is open (`data-state`, `open` by default) and done animating in.
- `waitForText($page, '[role="option"]', 'general')`: any matching element contains the text.
+ - `waitForCount($page, '@composer-media-item', 2)`: that many elements match (`===`, or pass `'>='` / `'>'`).
- `waitForGoneOrShown($page, gone: '@post-composer-dialog', shown: '@unsaved-changes-dialog')`: whichever happens first, so the assertion after it fails at once instead of waiting out the timeout.
- `waitForPath($page, $path)`: the page is at that path.
- `waitForCondition($page, $js)`: only for what is not about an element (`location.search`, a `window.__` spy).
- - Never write `document.querySelector(...)` inside a wait, and never define a per-file `waitFor*` helper. Pest's `Webpage` is `final readonly` and not macroable, which is why these are global functions. Files that still have their own `waitFor*` helpers predate this rule; move them to the shared helpers when touching them (the sweep is tracked in #435). If a wait needs something the helpers cannot express, add a helper to `tests/Pest.php` instead of inlining it.
+ - Each wait gives up after 30 seconds; a slower one (an import that polls the server) passes `seconds:` to `waitFor`, `waitForGone`, `waitForState` or `waitForCondition`.
+ - Never write `document.querySelector(...)` inside a wait, and never define a per-file `waitFor*` helper. Pest's `Webpage` is `final readonly` and not macroable, which is why these are global functions. A helper with a domain name (`waitForComposerReady`) may wrap one condition, built on the shared helpers, never a polling loop of its own. If a wait needs something the helpers cannot express, add a helper to `tests/Pest.php` instead of inlining it.
- **Never `sleep()` in a browser test.** The HTTP server that serves the page runs inside the same PHP process (an Amp loop that only ticks while Pest awaits Playwright), so a blocking `sleep()` starves every asset request: the page stays blank, the Vue app never mounts, and screenshots come out empty. The helpers above poll from the page with `$page->script(...)`, which keeps the loop running.
- `BrowserTestCase` sets `$fakesVite = false` on purpose: these tests load real built assets, so faking Vite blanks the app.
- End page assertions with `->assertNoJavaScriptErrors()`.
diff --git a/tests/Browser/ApiKeyCreateDialogTest.php b/tests/Browser/ApiKeyCreateDialogTest.php
index c7fd9dd0f..4a7f330f9 100644
--- a/tests/Browser/ApiKeyCreateDialogTest.php
+++ b/tests/Browser/ApiKeyCreateDialogTest.php
@@ -6,20 +6,6 @@ use App\Models\AccessToken;
use App\Models\User;
use App\Models\Workspace;
-function waitForApiKeyCreateTestId(mixed $page, string $testId): void
-{
- $page->script(<<<JS
- (async () => {
- const sel = '[data-testid="{$testId}"]';
- for (let i = 0; i < 150; i++) {
- const el = document.querySelector(sel);
- if (el && el.getBoundingClientRect().height > 0) return;
- await new Promise((r) => setTimeout(r, 50));
- }
- })();
- JS);
-}
-
test('the expiry date picker matches the dialog inputs and opens a calendar', function () {
$user = User::factory()->create();
$workspace = Workspace::factory()->create([
@@ -32,9 +18,9 @@ test('the expiry date picker matches the dialog inputs and opens a calendar', fu
$this->actingAs($user->fresh());
$page = visit(route('app.api-keys.index'));
- waitForApiKeyCreateTestId($page, 'api-keys-empty-create');
+ waitFor($page, '@api-keys-empty-create');
$page->click('@api-keys-empty-create');
- waitForApiKeyCreateTestId($page, 'token-expires-trigger');
+ waitFor($page, '@token-expires-trigger');
$page->assertScript(
"(() => { const a = document.getElementById('token-name').getBoundingClientRect(); const b = document.getElementById('token-expires').getBoundingClientRect(); return Math.round(a.height) === Math.round(b.height) && getComputedStyle(document.getElementById('token-expires')).fontWeight === '400'; })()",
@@ -42,7 +28,7 @@ test('the expiry date picker matches the dialog inputs and opens a calendar', fu
)->assertSeeIn('@token-expires-trigger', __('settings.api_keys.create_dialog.expires_placeholder'));
$page->click('@token-expires-trigger');
- waitForApiKeyCreateTestId($page, 'token-expires-calendar');
+ waitFor($page, '@token-expires-calendar');
$page->assertVisible('@token-expires-calendar')->assertNoJavaScriptErrors();
});
@@ -59,12 +45,12 @@ test('a generated key shows only its last four characters and copies without a t
$this->actingAs($user->fresh());
$page = visit(route('app.api-keys.index'));
- waitForApiKeyCreateTestId($page, 'api-keys-empty-create');
+ waitFor($page, '@api-keys-empty-create');
$page->click('@api-keys-empty-create');
- waitForApiKeyCreateTestId($page, 'token-name');
+ waitFor($page, '@token-name');
$page->fill('@token-name', 'Generated key');
$page->click('@create-api-key-submit');
- waitForApiKeyCreateTestId($page, 'api-key-generated-dialog');
+ waitFor($page, '@api-key-generated-dialog');
$page->assertVisible('@api-key-generated-input')
->assertScript("(() => { const dialog = document.querySelector('[data-testid=\"api-key-generated-dialog\"]'); const field = document.querySelector('[data-testid=\"api-key-generated-input\"]'); return dialog.scrollWidth <= dialog.clientWidth && field.getBoundingClientRect().right <= dialog.getBoundingClientRect().right; })()", true)
@@ -72,7 +58,7 @@ test('a generated key shows only its last four characters and copies without a t
$page->script('navigator.clipboard.writeText = async () => {};');
$page->click('@api-key-generated-copy');
- waitForApiKeyCreateTestId($page, 'api-key-generated-copied');
+ waitFor($page, '@api-key-generated-copied');
$page->assertVisible('@api-key-generated-copied')
->assertScript("document.querySelector('[data-sonner-toast]') === null", true)
@@ -96,7 +82,7 @@ test('a workspace without api keys shows only the centered illustration with a c
$this->actingAs(apiKeysPageAdmin());
$page = visit(route('app.api-keys.index'));
- waitForApiKeyCreateTestId($page, 'api-keys-empty');
+ waitFor($page, '@api-keys-empty');
$page->assertVisible('@api-keys-empty-illustration')
->assertSeeIn('@api-keys-empty', __('settings.api_keys.empty.title'))
@@ -122,7 +108,7 @@ test('a workspace with api keys keeps the header and the list at the top', funct
$this->actingAs($user);
$page = visit(route('app.api-keys.index'));
- waitForApiKeyCreateTestId($page, 'header-title');
+ waitFor($page, '@header-title');
$page->assertVisible('@create-api-key-button')
->assertMissing('@api-keys-empty')
@@ -145,7 +131,7 @@ test('api key rows show whether each key is active, expiring soon or expired', f
$this->actingAs($user);
$page = visit(route('app.api-keys.index'));
- waitForApiKeyCreateTestId($page, "api-key-row-{$expired->id}");
+ waitFor($page, "@api-key-row-{$expired->id}");
$page->assertSeeIn("@api-key-expiry-{$active->id}", __('settings.api_keys.meta.never_expires'));
diff --git a/tests/Browser/AuthLanguageSwitcherTest.php b/tests/Browser/AuthLanguageSwitcherTest.php
index cfe79bc37..1d10c9cc4 100644
--- a/tests/Browser/AuthLanguageSwitcherTest.php
+++ b/tests/Browser/AuthLanguageSwitcherTest.php
@@ -4,26 +4,12 @@ declare(strict_types=1);
use App\Models\User;
-function waitForAuthLanguageTestId(mixed $page, string $testId): void
-{
- $page->script(<<<JS
- (async () => {
- const sel = '[data-testid="{$testId}"]';
- for (let i = 0; i < 100; i++) {
- const el = document.querySelector(sel);
- if (el && el.getBoundingClientRect().height > 0) return;
- await new Promise((r) => setTimeout(r, 50));
- }
- })();
- JS);
-}
-
beforeEach(fn () => config(['trypost.self_hosted' => false]));
test('every logged-out auth screen offers the language switcher', function (string $route) {
$page = visit(route($route, $route === 'password.reset' ? ['token' => 'preview-token'] : []));
- waitForAuthLanguageTestId($page, 'language-picker-trigger');
+ waitFor($page, '@language-picker-trigger');
$page->assertVisible('@language-picker-trigger')->assertNoJavaScriptErrors();
})->with(['login']);
@@ -39,16 +25,16 @@ test('the switcher is hidden once the visitor is authenticated', function () {
test('the picked language survives navigating between auth screens', function () {
$page = visit(route('login'));
- waitForAuthLanguageTestId($page, 'language-picker-trigger');
+ waitFor($page, '@language-picker-trigger');
$page->click('@language-picker-trigger');
- waitForAuthLanguageTestId($page, 'language-picker-option-pt-BR');
+ waitFor($page, '@language-picker-option-pt-BR');
$page->click('@language-picker-option-pt-BR');
- waitForAuthLanguageTestId($page, 'language-picker-trigger');
+ waitFor($page, '@language-picker-trigger');
$page->assertSee('Entrar no TryPost');
$page->click('@login-sign-up-link');
- waitForAuthLanguageTestId($page, 'language-picker-trigger');
+ waitFor($page, '@language-picker-trigger');
$page->assertSee('Criar conta')->assertNoJavaScriptErrors();
});
diff --git a/tests/Browser/AuthStandardFormTest.php b/tests/Browser/AuthStandardFormTest.php
index 6c8a64445..546a8236f 100644
--- a/tests/Browser/AuthStandardFormTest.php
+++ b/tests/Browser/AuthStandardFormTest.php
@@ -2,25 +2,11 @@
declare(strict_types=1);
-function waitForAuthStandardFormTestId(mixed $page, string $testId): void
-{
- $page->script(<<<JS
- (async () => {
- const sel = '[data-testid="{$testId}"]';
- for (let i = 0; i < 100; i++) {
- const el = document.querySelector(sel);
- if (el && el.getBoundingClientRect().height > 0) return;
- await new Promise((r) => setTimeout(r, 50));
- }
- })();
- JS);
-}
-
test('the login form uses the standard control height and fits a 375px phone', function () {
config(['trypost.self_hosted' => false]);
$page = visit(route('login'))->resize(375, 812);
- waitForAuthStandardFormTestId($page, 'login-submit');
+ waitFor($page, '@login-submit');
$layout = $page->script(<<<'JS'
(() => {
@@ -51,7 +37,7 @@ test('the login form uses the standard control height and fits a 375px phone', f
test('on a phone the auth content sits in the middle of the screen with the legal line at the bottom', function () {
$page = visit(route('password.request'))->resize(390, 844);
- $page->script('new Promise((resolve) => { const check = () => document.querySelector("[data-testid=auth-logo]") ? resolve(true) : requestAnimationFrame(check); check(); })');
+ waitForState($page, '@auth-logo', 'true');
$layout = $page->script(<<<'JS'
(() => {
diff --git a/tests/Browser/AuthTitlesTest.php b/tests/Browser/AuthTitlesTest.php
index 5c862f2de..ea0a30ca3 100644
--- a/tests/Browser/AuthTitlesTest.php
+++ b/tests/Browser/AuthTitlesTest.php
@@ -2,57 +2,35 @@
declare(strict_types=1);
-function waitForAuthTitlesTestId(mixed $page, string $testId): void
-{
- $page->script(<<<JS
- (async () => {
- const selector = '[data-testid="{$testId}"]';
- for (let attempt = 0; attempt < 200; attempt++) {
- const element = document.querySelector(selector);
- if (element && element.getBoundingClientRect().height > 0) return;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })();
- JS);
-}
-
function waitForAuthTitlesRequirementMet(mixed $page, string $key, string $met): void
{
- $page->script(<<<JS
- (async () => {
- const selector = '[data-testid="password-requirement-{$key}"][data-met="{$met}"]';
- for (let attempt = 0; attempt < 200; attempt++) {
- if (document.querySelector(selector)) return;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })();
- JS);
+ waitForState($page, "@password-requirement-{$key}[data-met=\"{$met}\"]", 'true');
}
beforeEach(fn () => config(['trypost.self_hosted' => false]));
test('login shows the new title without a description and links to register', function () {
$page = visit(route('login'));
- waitForAuthTitlesTestId($page, 'login-sign-up-link');
+ waitFor($page, '@login-sign-up-link');
$page->assertSeeIn('@auth-title', 'Log in to TryPost')
->assertDontSee('Enter your email and password below to log in')
->click('@login-sign-up-link');
- waitForAuthTitlesTestId($page, 'register-log-in-link');
+ waitFor($page, '@register-log-in-link');
$page->assertSeeIn('@auth-title', 'Create a TryPost account')
->assertDontSee('Create your account and start scheduling posts across every network.')
->click('@register-log-in-link');
- waitForAuthTitlesTestId($page, 'login-sign-up-link');
+ waitFor($page, '@login-sign-up-link');
$page->assertSeeIn('@auth-title', 'Log in to TryPost')->assertNoJavaScriptErrors();
});
test('typing a password ticks each requirement', function () {
$page = visit(route('register'));
- waitForAuthTitlesTestId($page, 'password-requirements');
+ waitFor($page, '@password-requirements');
$page->assertSeeIn('@password-requirement-min', 'At least 12 characters')
->assertAttribute('@password-requirement-min', 'data-met', 'false')
diff --git a/tests/Browser/ChangelogTest.php b/tests/Browser/ChangelogTest.php
index 705a7ba2f..236d8d706 100644
--- a/tests/Browser/ChangelogTest.php
+++ b/tests/Browser/ChangelogTest.php
@@ -11,45 +11,14 @@ use App\Models\ChangelogEntryView;
use App\Models\User;
use App\Models\Workspace;
-function waitForChangelogCondition(mixed $page, string $condition): void
-{
- $page->script(<<<JS
- (async () => {
- for (let attempt = 0; attempt < 200; attempt++) {
- if ({$condition}) return;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })();
- JS);
-}
-
-function waitForChangelogTestId(mixed $page, string $testId): void
-{
- waitForChangelogCondition($page, "document.querySelector('[data-testid=\"{$testId}\"]')");
-}
-
-function waitForChangelogText(mixed $page, string $testId, string $text): void
-{
- waitForChangelogCondition($page, "document.querySelector('[data-testid=\"{$testId}\"]')?.textContent.includes('{$text}')");
-}
-
-function waitForChangelogTestIdGone(mixed $page, string $testId): void
-{
- waitForChangelogCondition($page, "!document.querySelector('[data-testid=\"{$testId}\"]')");
-}
-
function waitForChangelogViews(mixed $page, User $user, int $count): void
{
- for ($attempt = 0; $attempt < 100 && ChangelogEntryView::where('user_id', $user->id)->count() < $count; $attempt++) {
- $page->script('new Promise((resolve) => setTimeout(resolve, 50))');
- }
+ waitForDatabase($page, fn () => ChangelogEntryView::where('user_id', $user->id)->count() >= $count);
}
function waitForChangelogReaction(mixed $page, ChangelogEntry $entry, ?Reaction $reaction): void
{
- for ($attempt = 0; $attempt < 100 && ChangelogEntryView::where('changelog_entry_id', $entry->id)->value('reaction') !== $reaction?->value; $attempt++) {
- $page->script('new Promise((resolve) => setTimeout(resolve, 50))');
- }
+ waitForDatabase($page, fn () => ChangelogEntryView::where('changelog_entry_id', $entry->id)->value('reaction') === $reaction?->value);
}
function createChangelogUser(array $attributes = []): User
@@ -112,30 +81,30 @@ test('opening the sidebar card shows the newest entry, records the view, hides t
$this->actingAs($user->fresh());
$page = visit(route('app.calendar'))->resize(1280, 900);
- waitForChangelogText($page, 'changelog-card-title', 'Newest feature');
+ waitForText($page, '@changelog-card-title', 'Newest feature');
expect($page->script("document.querySelector('[data-testid=\"changelog-card\"] [data-testid^=\"changelog-tag-\"]') === null"))->toBeTrue();
$page->click('@changelog-card');
- waitForChangelogText($page, 'changelog-entry-title', 'Newest feature');
+ waitForText($page, '@changelog-entry-title', 'Newest feature');
$page->assertSeeIn('@changelog-entry', 'The newest feature body.')
->assertSeeIn('@changelog-entry-tags', 'New')
->assertSeeIn('@changelog-entry-tags', 'Beta')
->assertSeeIn('@changelog-back', 'All updates');
expect($page->script("document.querySelector('[data-testid=\"changelog-dialog\"]').getAttribute('aria-labelledby') && document.getElementById(document.querySelector('[data-testid=\"changelog-dialog\"]').getAttribute('aria-labelledby')).textContent.trim()"))
->toBe('Newest feature');
- waitForChangelogTestIdGone($page, 'changelog-card');
+ waitForGone($page, '@changelog-card');
expect(ChangelogEntryView::where('user_id', $user->id)->pluck('changelog_entry_id')->all())
->toBe([$newest->id]);
$page->click('@changelog-back');
- waitForChangelogTestId($page, 'changelog-item-2026-10-13-older');
+ waitForState($page, '@changelog-item-2026-10-13-older', 'true');
$page->assertPresent('@changelog-unseen-2026-10-13-older')
->assertMissing('@changelog-unseen-2026-10-14-newest');
$page->click('@changelog-item-2026-10-13-older');
- waitForChangelogText($page, 'changelog-entry-title', 'Older feature');
+ waitForText($page, '@changelog-entry-title', 'Older feature');
waitForChangelogViews($page, $user, 2);
expect(ChangelogEntryView::where('user_id', $user->id)->pluck('changelog_entry_id')->sort()->values()->all())
@@ -158,7 +127,7 @@ test('opening the sidebar card shows the newest entry, records the view, hides t
expect(ChangelogEntryView::where('changelog_entry_id', $older->id)->sole()->reaction)->toBeNull();
$page->click('@changelog-close');
- waitForChangelogTestIdGone($page, 'changelog-dialog');
+ waitForGone($page, '@changelog-dialog');
$page->assertMissing('@changelog-card')
->assertMissing('@changelog-dialog')
@@ -177,7 +146,7 @@ test('the help menu item is translated and opens the list', function () {
$this->actingAs($user->fresh());
$page = visit(route('app.calendar'))->resize(1280, 900);
- waitForChangelogTestId($page, 'sidebar-workspace-menu');
+ waitForState($page, '@sidebar-workspace-menu', 'true');
openChangelogHelpMenu($page);
@@ -185,7 +154,7 @@ test('the help menu item is translated and opens the list', function () {
expect(__('sidebar.support.changelog', [], 'pt-BR'))->toBe('Novidades');
$page->click('@sidebar-support-changelog');
- waitForChangelogTestId($page, 'changelog-item-2026-10-13-listed');
+ waitForState($page, '@changelog-item-2026-10-13-listed', 'true');
$page->assertPresent('@changelog-unseen-2026-10-13-listed')
->assertMissing('@changelog-card')
@@ -206,27 +175,27 @@ test('hovering a list item highlights it, only hovering its cover zooms the cove
$this->actingAs($user->fresh());
$page = visit(route('app.calendar'))->resize(1280, 900);
- waitForChangelogTestId($page, 'sidebar-workspace-menu');
+ waitForState($page, '@sidebar-workspace-menu', 'true');
openChangelogHelpMenu($page);
$page->click('@sidebar-support-changelog');
- waitForChangelogTestId($page, 'changelog-item-cover-2026-10-13-hovered');
+ waitForState($page, '@changelog-item-cover-2026-10-13-hovered', 'true');
$coverScale = "getComputedStyle(document.querySelector('[data-testid=\"changelog-item-zoom-2026-10-13-hovered\"]')).scale";
$itemBackground = "getComputedStyle(document.querySelector('[data-testid=\"changelog-item-2026-10-13-hovered\"]')).backgroundColor";
$idleBackground = $page->script($itemBackground);
$page->hover('@changelog-item-title-2026-10-13-hovered');
- waitForChangelogCondition($page, "{$itemBackground} !== '{$idleBackground}'");
+ waitForState($page, '@changelog-item-2026-10-13-hovered', "getComputedStyle(element).backgroundColor !== '{$idleBackground}'");
expect($page->script($itemBackground))->not->toBe($idleBackground)
->and($page->script($coverScale))->toBe('none');
$page->hover('@changelog-item-cover-2026-10-13-hovered');
- waitForChangelogCondition($page, "{$coverScale} === '1.04'");
+ waitForState($page, '@changelog-item-zoom-2026-10-13-hovered', "getComputedStyle(element).scale === '1.04'");
expect($page->script($coverScale))->toBe('1.04');
$page->click('@changelog-item-title-2026-10-13-hovered');
- waitForChangelogText($page, 'changelog-entry-title', 'Hovered feature');
+ waitForText($page, '@changelog-entry-title', 'Hovered feature');
$page->assertSeeIn('@changelog-entry-title', 'Hovered feature')
->assertNoJavaScriptErrors();
@@ -244,30 +213,30 @@ test('the list loads the next page on scroll, reopens on the list and shows an e
$this->actingAs($user->fresh());
$page = visit(route('app.calendar'))->resize(1280, 900);
- waitForChangelogTestId($page, 'sidebar-workspace-menu');
+ waitForState($page, '@sidebar-workspace-menu', 'true');
openChangelogHelpMenu($page);
$page->click('@sidebar-support-changelog');
- waitForChangelogTestId($page, 'changelog-item-2026-09-01-paged');
+ waitForState($page, '@changelog-item-2026-09-01-paged', 'true');
expect($page->script("document.querySelectorAll('[data-testid^=\"changelog-item-cover-\"]').length"))->toBe(5);
$page->script("document.querySelector('[data-testid=\"changelog-dialog\"]').scrollTop = 100000");
- waitForChangelogTestId($page, 'changelog-item-2026-09-07-paged');
+ waitForState($page, '@changelog-item-2026-09-07-paged', 'true');
expect($page->script("document.querySelectorAll('[data-testid^=\"changelog-item-cover-\"]').length"))->toBe(7);
$page->click('@changelog-item-title-2026-09-07-paged');
- waitForChangelogTestId($page, 'changelog-entry');
- waitForChangelogCondition($page, "document.querySelector('[data-testid=\"changelog-dialog\"]').scrollTop === 0");
+ waitForState($page, '@changelog-entry', 'true');
+ waitForState($page, '@changelog-dialog', 'element.scrollTop === 0');
expect($page->script("document.querySelector('[data-testid=\"changelog-dialog\"]').scrollTop"))->toBe(0);
$page->click('@changelog-close');
- waitForChangelogTestIdGone($page, 'changelog-dialog');
+ waitForGone($page, '@changelog-dialog');
openChangelogHelpMenu($page);
$page->click('@sidebar-support-changelog');
- waitForChangelogTestId($page, 'changelog-item-2026-09-01-paged');
- waitForChangelogCondition($page, "document.querySelectorAll('[data-testid^=\"changelog-item-cover-\"]').length === 5");
+ waitForState($page, '@changelog-item-2026-09-01-paged', 'true');
+ waitForCount($page, '[data-testid^="changelog-item-cover-"]', 5);
expect($page->script("document.querySelectorAll('[data-testid^=\"changelog-item-cover-\"]').length"))->toBe(5);
$page->assertMissing('@changelog-entry')
@@ -276,10 +245,10 @@ test('the list loads the next page on scroll, reopens on the list and shows an e
ChangelogEntry::query()->delete();
$empty = visit(route('app.calendar'))->resize(1280, 900);
- waitForChangelogTestId($empty, 'sidebar-workspace-menu');
+ waitForState($empty, '@sidebar-workspace-menu', 'true');
openChangelogHelpMenu($empty);
$empty->click('@sidebar-support-changelog');
- waitForChangelogTestId($empty, 'changelog-empty');
+ waitForState($empty, '@changelog-empty', 'true');
$empty->assertSeeIn('@changelog-empty', 'Nothing new yet')
->assertNoJavaScriptErrors();
@@ -294,17 +263,17 @@ test('a reaction that fails to save is undone and explained', function () {
$this->actingAs($user->fresh());
$page = visit(route('app.calendar'))->resize(1280, 900);
- waitForChangelogTestId($page, 'sidebar-workspace-menu');
+ waitForState($page, '@sidebar-workspace-menu', 'true');
openChangelogHelpMenu($page);
$page->click('@sidebar-support-changelog');
- waitForChangelogTestId($page, 'changelog-item-title-2026-10-13-failing');
+ waitForState($page, '@changelog-item-title-2026-10-13-failing', 'true');
$page->click('@changelog-item-title-2026-10-13-failing');
- waitForChangelogTestId($page, 'changelog-reaction-like');
+ waitForState($page, '@changelog-reaction-like', 'true');
waitForChangelogViews($page, $user, 1);
$entry->delete();
$page->click('@changelog-reaction-like');
- waitForChangelogCondition($page, "document.body.innerText.includes(\"Couldn't save your answer\")");
+ waitForCondition($page, "document.body.innerText.includes(\"Couldn't save your answer\")");
expect($page->script("document.querySelector('[data-testid=\"changelog-reaction-like\"]').getAttribute('aria-pressed')"))->toBe('false');
$page->assertSee("Couldn't save your answer. Try again.");
@@ -319,7 +288,7 @@ test('nothing of the changelog shows when it is turned off', function () {
$this->actingAs($user->fresh());
$page = visit(route('app.calendar'))->resize(1280, 900);
- waitForChangelogTestId($page, 'sidebar-workspace-menu');
+ waitForState($page, '@sidebar-workspace-menu', 'true');
$page->script(<<<'JS'
(async () => {
const find = async (testId) => {
@@ -352,12 +321,12 @@ test('a second reaction click while the first is saving is ignored', function ()
$this->actingAs($user->fresh());
$page = visit(route('app.calendar'))->resize(1280, 900);
- waitForChangelogTestId($page, 'sidebar-workspace-menu');
+ waitForState($page, '@sidebar-workspace-menu', 'true');
openChangelogHelpMenu($page);
$page->click('@sidebar-support-changelog');
- waitForChangelogTestId($page, 'changelog-item-title-2026-10-13-double');
+ waitForState($page, '@changelog-item-title-2026-10-13-double', 'true');
$page->click('@changelog-item-title-2026-10-13-double');
- waitForChangelogTestId($page, 'changelog-reaction-like');
+ waitForState($page, '@changelog-reaction-like', 'true');
waitForChangelogViews($page, $user, 1);
$page->script("document.querySelector('[data-testid=\"changelog-reaction-like\"]').click(); document.querySelector('[data-testid=\"changelog-reaction-dislike\"]').click();");
@@ -380,30 +349,30 @@ test('a browser Back closes the modal, and reopening shows a fresh list', functi
$this->actingAs($user->fresh());
$page = visit(route('app.calendar'))->navigate(route('app.calendar'))->resize(1280, 900);
- waitForChangelogTestId($page, 'sidebar-workspace-menu');
+ waitForState($page, '@sidebar-workspace-menu', 'true');
openChangelogHelpMenu($page);
$page->click('@sidebar-support-changelog');
- waitForChangelogTestId($page, 'changelog-unseen-2026-10-13-fresh');
+ waitForState($page, '@changelog-unseen-2026-10-13-fresh', 'true');
$page->click('@changelog-item-title-2026-10-13-fresh');
waitForChangelogViews($page, $user, 1);
$page->click('@changelog-close');
- waitForChangelogTestIdGone($page, 'changelog-dialog');
+ waitForGone($page, '@changelog-dialog');
$page->script("document.querySelector('[data-testid=\"nav-{$insightsPath}\"]').click()");
- waitForChangelogCondition($page, "location.pathname === '{$insightsPath}'");
+ waitForPath($page, $insightsPath);
openChangelogHelpMenu($page);
$page->click('@sidebar-support-changelog');
- waitForChangelogTestId($page, 'changelog-item-2026-10-13-fresh');
+ waitForState($page, '@changelog-item-2026-10-13-fresh', 'true');
$page->back();
- waitForChangelogCondition($page, "location.pathname === '{$calendarPath}'");
- waitForChangelogTestIdGone($page, 'changelog-dialog');
+ waitForPath($page, $calendarPath);
+ waitForGone($page, '@changelog-dialog');
$page->assertPathIs($calendarPath)->assertMissing('@changelog-dialog');
openChangelogHelpMenu($page);
$page->click('@sidebar-support-changelog');
- waitForChangelogTestId($page, 'changelog-item-2026-10-13-fresh');
+ waitForState($page, '@changelog-item-2026-10-13-fresh', 'true');
$page->assertMissing('@changelog-unseen-2026-10-13-fresh')
->assertNoJavaScriptErrors();
@@ -420,15 +389,15 @@ test('a browser Back between two entries of the same page closes the modal too',
$this->actingAs($user->fresh());
$page = visit(route('app.calendar'))->navigate(route('app.calendar'))->resize(1280, 900);
- waitForChangelogTestId($page, 'sidebar-workspace-menu');
+ waitForState($page, '@sidebar-workspace-menu', 'true');
$page->script('window.history.pushState(window.history.state, "", location.href)');
openChangelogHelpMenu($page);
$page->click('@sidebar-support-changelog');
- waitForChangelogTestId($page, 'changelog-item-2026-10-13-same');
+ waitForState($page, '@changelog-item-2026-10-13-same', 'true');
$page->back();
- waitForChangelogTestIdGone($page, 'changelog-dialog');
+ waitForGone($page, '@changelog-dialog');
$page->assertPathIs(route('app.calendar', absolute: false))
->assertMissing('@changelog-dialog')
@@ -444,16 +413,16 @@ test('an open that fails to record keeps the entry marked as unseen', function (
$this->actingAs($user->fresh());
$page = visit(route('app.calendar'))->resize(1280, 900);
- waitForChangelogTestId($page, 'sidebar-workspace-menu');
+ waitForState($page, '@sidebar-workspace-menu', 'true');
openChangelogHelpMenu($page);
$page->click('@sidebar-support-changelog');
- waitForChangelogTestId($page, 'changelog-unseen-2026-10-13-unrecorded');
+ waitForState($page, '@changelog-unseen-2026-10-13-unrecorded', 'true');
$entry->update(['published_on' => today()->addDay()]);
$page->click('@changelog-item-title-2026-10-13-unrecorded');
- waitForChangelogTestId($page, 'changelog-entry');
+ waitForState($page, '@changelog-entry', 'true');
$page->click('@changelog-back');
- waitForChangelogTestId($page, 'changelog-unseen-2026-10-13-unrecorded');
+ waitForState($page, '@changelog-unseen-2026-10-13-unrecorded', 'true');
$page->assertPresent('@changelog-unseen-2026-10-13-unrecorded');
expect(ChangelogEntryView::count())->toBe(0);
diff --git a/tests/Browser/ChannelGridTest.php b/tests/Browser/ChannelGridTest.php
index d9b9f3f4a..a38ebf83d 100644
--- a/tests/Browser/ChannelGridTest.php
+++ b/tests/Browser/ChannelGridTest.php
@@ -13,20 +13,6 @@ use Carbon\CarbonInterface;
const CHANNEL_GRID_PIXEL = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==';
-function waitForChannelGridTestId(mixed $page, string $testId): void
-{
- $page->script(<<<JS
- (async () => {
- const selector = '[data-testid="{$testId}"]';
- for (let attempt = 0; attempt < 300; attempt++) {
- const element = document.querySelector(selector);
- if (element && element.getBoundingClientRect().height > 0) return;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })();
- JS);
-}
-
function channelGridBrowserUser(): User
{
$user = User::factory()->create(['timezone' => 'UTC', 'locale' => Locale::DEFAULT]);
@@ -76,12 +62,12 @@ test('an instagram channel offers the grid view and the grid lays posts out in t
$this->actingAs($this->user);
$page = visit(route('app.channels.publish', $this->instagram));
- waitForChannelGridTestId($page, 'schedule-view-grid');
+ waitFor($page, '@schedule-view-grid');
$page->assertVisible('@schedule-view-grid')
->click('@schedule-view-grid');
- waitForChannelGridTestId($page, 'channel-grid');
+ waitFor($page, '@channel-grid');
$page->assertPathIs(route('app.channels.grid', $this->instagram, false))
->assertVisible("@grid-tile-{$reel->id}")
@@ -105,7 +91,7 @@ test('an instagram channel offers the grid view and the grid lays posts out in t
expect(array_unique($tops))->toHaveCount(1);
$page->hover("@grid-tile-{$reel->id}");
- waitForChannelGridTestId($page, "grid-tile-tooltip-{$reel->id}");
+ waitFor($page, "@grid-tile-tooltip-{$reel->id}");
expect(trim((string) $page->script("document.querySelector('[data-testid=\"grid-tile-tooltip-{$reel->id}\"] [role=\"tooltip\"]').textContent")))
->toBe("This post was sent {$reel->published_at->format('F j, Y \\a\\t g:i A')}");
@@ -121,7 +107,7 @@ test('the grid sits under the shared channel header, which stays put while the g
$this->actingAs($this->user);
$page = visit(route('app.channels.grid', $this->instagram));
- waitForChannelGridTestId($page, 'channel-grid');
+ waitFor($page, '@channel-grid');
$page->assertVisible('@header-title')
->assertVisible('@channel-grid-divider')
@@ -142,7 +128,7 @@ test('the grid sits under the shared channel header, which stays put while the g
->and($after)->toBe($before);
$page->hover('@schedule-view-grid');
- waitForChannelGridTestId($page, 'schedule-view-grid-note');
+ waitFor($page, '@schedule-view-grid-note');
expect(trim((string) $page->script('document.querySelector(\'[data-testid="schedule-view-grid-note"] [role="tooltip"]\').textContent')))
->toBe('This is an approximation of your post grid. It may differ on other devices, and posts published directly on Instagram update when we sync them.');
@@ -156,24 +142,24 @@ test('the grid keeps the schedule view switch and the new post button', function
$this->actingAs($this->user);
$page = visit(route('app.channels.grid', $this->instagram));
- waitForChannelGridTestId($page, 'schedule-view-grid');
+ waitFor($page, '@schedule-view-grid');
$page->assertAttribute('@schedule-view-grid', 'aria-current', 'page')
->assertAttributeMissing('@schedule-view-list', 'aria-current')
->assertVisible('@schedule-view-calendar')
->click('@posts-new-post');
- waitForChannelGridTestId($page, 'post-composer-dialog');
- waitForChannelGridTestId($page, "composer-account-{$this->instagram->id}");
+ waitFor($page, '@post-composer-dialog');
+ waitFor($page, "@composer-account-{$this->instagram->id}");
$page->assertVisible('@post-composer-dialog')
->assertVisible("@composer-account-{$this->instagram->id}")
->assertPathIs(route('app.channels.grid', $this->instagram, false));
$page = visit(route('app.channels.grid', $this->instagram));
- waitForChannelGridTestId($page, 'schedule-view-list');
+ waitFor($page, '@schedule-view-list');
$page->click('@schedule-view-list');
- waitForChannelGridTestId($page, 'publish-page');
+ waitFor($page, '@publish-page');
$page->assertPathIs(route('app.channels.publish', $this->instagram, false))
->assertAttribute('@schedule-view-list', 'aria-current', 'page')
@@ -186,10 +172,10 @@ test('clicking a carousel tile opens its media in the lightbox', function () {
$this->actingAs($this->user);
$page = visit(route('app.channels.grid', $this->instagram));
- waitForChannelGridTestId($page, "grid-tile-{$carousel->id}");
+ waitFor($page, "@grid-tile-{$carousel->id}");
$page->click("@grid-tile-{$carousel->id}");
- waitForChannelGridTestId($page, 'media-lightbox-counter');
+ waitFor($page, '@media-lightbox-counter');
$page->assertVisible('@media-lightbox')
->assertVisible('@media-lightbox-image')
@@ -207,9 +193,9 @@ test('the grid tooltip shows the sent time in the user zone, not the browser zon
$this->actingAs($this->user);
$page = visit(route('app.channels.grid', $this->instagram));
- waitForChannelGridTestId($page, "grid-tile-{$reel->id}");
+ waitFor($page, "@grid-tile-{$reel->id}");
$page->hover("@grid-tile-{$reel->id}");
- waitForChannelGridTestId($page, "grid-tile-tooltip-{$reel->id}");
+ waitFor($page, "@grid-tile-tooltip-{$reel->id}");
expect(trim((string) $page->script("document.querySelector('[data-testid=\"grid-tile-tooltip-{$reel->id}\"] [role=\"tooltip\"]').textContent")))
->toBe("This post was sent {$reel->published_at->setTimezone('Asia/Tokyo')->format('F j, Y \\a\\t g:i A')}");
diff --git a/tests/Browser/ChannelInsightsFiltersTest.php b/tests/Browser/ChannelInsightsFiltersTest.php
index 85b0d732d..8a1abb5c6 100644
--- a/tests/Browser/ChannelInsightsFiltersTest.php
+++ b/tests/Browser/ChannelInsightsFiltersTest.php
@@ -17,32 +17,6 @@ use App\Models\WorkspaceLabel;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\Queue;
-function waitForInsightsFilterTestId(mixed $page, string $testId): void
-{
- $page->script(<<<JS
- (async () => {
- const selector = '[data-testid="{$testId}"]';
- for (let attempt = 0; attempt < 600; attempt++) {
- const element = document.querySelector(selector);
- if (element && element.getBoundingClientRect().height > 0) return;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })();
- JS);
-}
-
-function waitForInsightsFilterScript(mixed $page, string $condition): void
-{
- $page->script(<<<JS
- (async () => {
- for (let attempt = 0; attempt < 200; attempt++) {
- if ({$condition}) return;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })();
- JS);
-}
-
function insightsFilterPublication(SocialAccount $account, User $user, CarbonImmutable $publishedAt, int $reactions, ?ContentType $contentType, ?WorkspaceLabel $label = null, PublicationContentType $publicationType = PublicationContentType::Image): AnalyticsPublication
{
$post = null;
@@ -98,22 +72,25 @@ beforeEach(function () {
test('the post type filter lists this platform types and narrows the URL and the totals', function () {
$page = visit(route('app.channels.insights', $this->instagram));
- waitForInsightsFilterTestId($page, 'insights-post-type-filter');
+ waitFor($page, '@insights-post-type-filter');
$page->assertScript('document.querySelectorAll("#insights-posts-body tr").length', 3)
->click('@insights-post-type-filter');
- waitForInsightsFilterTestId($page, 'insights-post-type-option-instagram_story');
+ waitFor($page, '@insights-post-type-option-instagram_story');
$page->assertScript('Array.from(document.querySelectorAll("[data-testid^=insights-post-type-option-]")).map((element) => element.dataset.testid.replace("insights-post-type-option-", "")).join(",")', 'instagram_feed,instagram_reel,instagram_story')
->click('@insights-post-type-option-instagram_story');
- waitForInsightsFilterScript($page, 'Array.from(new URLSearchParams(location.search)).filter(([key]) => key.startsWith("types[")).map(([, value]) => value).join(",") === "instagram_story" && document.querySelectorAll("#insights-posts-body tr").length === 1 && document.querySelector("[data-testid=insights-card-posts] .font-heading").textContent.trim() === "1"');
+ waitForCondition($page, 'Array.from(new URLSearchParams(location.search)).filter(([key]) => key.startsWith("types[")).map(([, value]) => value).join(",") === "instagram_story"');
+ waitForCount($page, '#insights-posts-body tr', 1);
+ waitForState($page, '@insights-card-posts .font-heading', "element.textContent.trim() === '1'");
$page->assertScript('Array.from(new URLSearchParams(location.search)).filter(([key]) => key.startsWith("types[")).map(([, value]) => value).join(",")', 'instagram_story')
->assertScript('document.querySelectorAll("#insights-posts-body tr").length', 1)
->assertPresent("@insights-posts-row-{$this->story->id}")
->assertScript('document.querySelector("[data-testid=insights-card-posts] .font-heading").textContent.trim()', '1')
->click('@insights-post-type-clear');
- waitForInsightsFilterScript($page, '!location.search.includes("types") && document.querySelectorAll("#insights-posts-body tr").length === 3');
+ waitForCondition($page, '!location.search.includes("types")');
+ waitForCount($page, '#insights-posts-body tr', 3);
$page->assertScript('location.search.includes("types")', false)
->assertScript('document.querySelectorAll("#insights-posts-body tr").length', 3)
@@ -122,19 +99,21 @@ test('the post type filter lists this platform types and narrows the URL and the
test('history navigation re-syncs the label filter with the page', function () {
$page = visit(route('app.channels.insights', $this->instagram));
- waitForInsightsFilterTestId($page, 'insights-label-filter');
+ waitFor($page, '@insights-label-filter');
$page->script('window.__labelTrigger0 = document.querySelector("[data-testid=insights-label-filter]").textContent.trim()');
$page->click('@insights-range-7d');
- waitForInsightsFilterScript($page, 'new URLSearchParams(location.search).get("range") === "7d"');
+ waitForQueryParameter($page, 'range', '7d');
$page->click('@insights-label-filter');
- waitForInsightsFilterTestId($page, "insights-label-option-{$this->label->id}");
+ waitFor($page, "@insights-label-option-{$this->label->id}");
$page->click("@insights-label-option-{$this->label->id}");
- waitForInsightsFilterScript($page, 'location.search.includes("labels") && document.querySelectorAll("#insights-posts-body tr").length === 1');
+ waitForCondition($page, 'location.search.includes("labels")');
+ waitForCount($page, '#insights-posts-body tr', 1);
$page->assertScript('document.querySelector("[data-testid=insights-label-filter]").textContent.trim() !== window.__labelTrigger0', true);
$page->script('history.back()');
- waitForInsightsFilterScript($page, '!location.search.includes("range=7d") && !location.search.includes("labels") && document.querySelectorAll("#insights-posts-body tr").length === 3');
+ waitForCondition($page, '!location.search.includes("range=7d") && !location.search.includes("labels")');
+ waitForCount($page, '#insights-posts-body tr', 3);
$page->assertScript('document.querySelector("[data-testid=insights-label-filter]").textContent.trim() === window.__labelTrigger0', true)
->assertNoJavaScriptErrors();
@@ -142,7 +121,7 @@ test('history navigation re-syncs the label filter with the page', function () {
test('on a phone both filters show only their icon and chevron', function () {
$page = visit(route('app.channels.insights', $this->instagram))->resize(390, 844);
- waitForInsightsFilterTestId($page, 'insights-post-type-filter');
+ waitFor($page, '@insights-post-type-filter');
foreach (['insights-label-filter', 'insights-post-type-filter'] as $filter) {
$page->assertScript("Array.from(document.querySelectorAll('[data-testid=\"{$filter}\"] > span')).filter((element) => element.getBoundingClientRect().width > 0 && element.textContent.trim() !== '').length", 0)
@@ -155,12 +134,12 @@ test('on a phone both filters show only their icon and chevron', function () {
test('the post type filter search matches each word typed in any order and ignores case', function () {
$page = visit(route('app.channels.insights', $this->instagram));
- waitForInsightsFilterTestId($page, 'insights-post-type-filter');
+ waitFor($page, '@insights-post-type-filter');
$page->click('@insights-post-type-filter');
- waitForInsightsFilterTestId($page, 'insights-post-type-search');
+ waitFor($page, '@insights-post-type-search');
$page->type('@insights-post-type-search', 'POST feed');
- waitForInsightsFilterScript($page, '!document.querySelector("[data-testid=insights-post-type-option-instagram_reel]")');
+ waitForGone($page, '@insights-post-type-option-instagram_reel');
$page->assertScript('Array.from(document.querySelectorAll("[data-testid^=insights-post-type-option-]")).map((element) => element.dataset.testid.replace("insights-post-type-option-", "")).join(",")', 'instagram_feed')
->assertNoJavaScriptErrors();
@@ -171,7 +150,7 @@ test('a YouTube channel shows no post type filter and no type tag', function (Pl
$publication = insightsFilterPublication($channel, $this->user, CarbonImmutable::today('UTC')->subDays(2)->setTime(10, 0), 10, $contentType, publicationType: $publicationType);
$page = visit(route('app.channels.insights', $channel));
- waitForInsightsFilterTestId($page, "insights-posts-row-{$publication->id}");
+ waitFor($page, "@insights-posts-row-{$publication->id}");
$page->assertVisible('@insights-label-filter')
->assertMissing('@insights-post-type-filter')
@@ -186,7 +165,7 @@ test('a channel without the post type filter keeps the type tag', function (Plat
$publication = insightsFilterPublication($channel, $this->user, CarbonImmutable::today('UTC')->subDays(2)->setTime(10, 0), 10, $contentType, publicationType: PublicationContentType::Video);
$page = visit(route('app.channels.insights', $channel));
- waitForInsightsFilterTestId($page, "insights-posts-row-{$publication->id}");
+ waitFor($page, "@insights-posts-row-{$publication->id}");
$page->assertVisible('@insights-label-filter')
->assertMissing('@insights-post-type-filter')
@@ -204,7 +183,7 @@ test('a TikTok channel keeps the post type filter but shows no type tag', functi
$publication = insightsFilterPublication($channel, $this->user, CarbonImmutable::today('UTC')->subDays(2)->setTime(10, 0), 10, ContentType::TikTokPhoto, publicationType: PublicationContentType::Video);
$page = visit(route('app.channels.insights', $channel));
- waitForInsightsFilterTestId($page, "insights-posts-row-{$publication->id}");
+ waitFor($page, "@insights-posts-row-{$publication->id}");
$page->assertVisible('@insights-post-type-filter')
->assertMissing("@insights-posts-type-{$publication->id}")
@@ -213,9 +192,9 @@ test('a TikTok channel keeps the post type filter but shows no type tag', functi
test('the post type filter leaves a gap between the search and the first type', function () {
$page = visit(route('app.channels.insights', $this->instagram));
- waitForInsightsFilterTestId($page, 'insights-post-type-filter');
+ waitFor($page, '@insights-post-type-filter');
$page->click('@insights-post-type-filter');
- waitForInsightsFilterTestId($page, 'insights-post-type-option-instagram_feed');
+ waitFor($page, '@insights-post-type-option-instagram_feed');
$page->assertScript('document.querySelector("[data-testid=insights-post-type-option-instagram_feed]").getBoundingClientRect().top - document.querySelector("[data-testid=insights-post-type-search]").getBoundingClientRect().bottom >= 8', true)
->assertNoJavaScriptErrors();
@@ -226,12 +205,12 @@ test('a type already in the URL keeps the post type filter on a network without
$publication = insightsFilterPublication($channel, $this->user, CarbonImmutable::today('UTC')->subDays(2)->setTime(10, 0), 10, ContentType::ThreadsPost);
$page = visit(route('app.channels.insights', ['account' => $channel, 'types' => [ContentType::ThreadsGhostPost->value]]));
- waitForInsightsFilterTestId($page, 'insights-post-type-filter');
+ waitFor($page, '@insights-post-type-filter');
$page->click('@insights-post-type-filter');
- waitForInsightsFilterTestId($page, 'insights-post-type-clear');
+ waitFor($page, '@insights-post-type-clear');
$page->click('@insights-post-type-clear');
- waitForInsightsFilterTestId($page, "insights-posts-row-{$publication->id}");
+ waitFor($page, "@insights-posts-row-{$publication->id}");
$page->assertVisible("@insights-posts-row-{$publication->id}")
->assertMissing('@insights-post-type-filter')
diff --git a/tests/Browser/ChannelInsightsTest.php b/tests/Browser/ChannelInsightsTest.php
index 45d504900..3fc1a3e5d 100644
--- a/tests/Browser/ChannelInsightsTest.php
+++ b/tests/Browser/ChannelInsightsTest.php
@@ -19,32 +19,6 @@ use App\Models\Workspace;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\Queue;
-function waitForChannelInsightsTestId(mixed $page, string $testId): void
-{
- $page->script(<<<JS
- (async () => {
- const selector = '[data-testid="{$testId}"]';
- for (let attempt = 0; attempt < 600; attempt++) {
- const element = document.querySelector(selector);
- if (element && element.getBoundingClientRect().height > 0) return;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })();
- JS);
-}
-
-function waitForChannelInsightsScript(mixed $page, string $condition): void
-{
- $page->script(<<<JS
- (async () => {
- for (let attempt = 0; attempt < 200; attempt++) {
- if ({$condition}) return;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })();
- JS);
-}
-
function channelInsightsBrowserUser(): User
{
$user = User::factory()->create();
@@ -121,10 +95,10 @@ beforeEach(function () {
test('a range preset reloads the page with that range and keeps the table state', function () {
$page = visit(route('app.channels.insights', ['account' => $this->instagram, 'sort' => 'views', 'period' => 'previous']));
- waitForChannelInsightsTestId($page, 'insights-range-7d');
+ waitFor($page, '@insights-range-7d');
$page->click('@insights-range-7d');
- waitForChannelInsightsScript($page, 'new URLSearchParams(location.search).get("range") === "7d"');
+ waitForQueryParameter($page, 'range', '7d');
$page->assertScript('new URLSearchParams(location.search).get("range")', '7d')
->assertScript('new URLSearchParams(location.search).get("sort")', 'views')
@@ -145,7 +119,7 @@ test('finishing the import refreshes the available metrics and the publication t
]);
$page = visit(route('app.channels.insights', $fresh));
- waitForChannelInsightsTestId($page, 'insights-no-data');
+ waitFor($page, '@insights-no-data');
$page->assertVisible('@insights-no-data')
->assertMissing('@date-range-picker-trigger');
@@ -154,7 +128,7 @@ test('finishing the import refreshes the available metrics and the publication t
'saves_count' => 4,
]);
$state->update(['status' => SyncStatus::Complete]);
- waitForChannelInsightsTestId($page, "insights-posts-row-{$publication->id}");
+ waitFor($page, "@insights-posts-row-{$publication->id}");
$page->assertVisible("@insights-posts-row-{$publication->id}")
->assertVisible('@insights-card-saves')
@@ -168,10 +142,10 @@ test('the channel header exports this channel and rows open the post details or
$this->mostViews->update(['permalink' => 'https://www.instagram.com/p/most-views/']);
$page = visit(route('app.channels.insights', ['account' => $this->instagram, 'range' => '7d']));
- waitForChannelInsightsTestId($page, 'insights-export');
+ waitFor($page, '@insights-export');
$page->click('@insights-export');
- waitForChannelInsightsTestId($page, 'insights-export-csv');
+ waitFor($page, '@insights-export-csv');
$href = (string) $page->script('document.querySelector("[data-testid=insights-export-csv]").getAttribute("href")');
parse_str((string) parse_url($href, PHP_URL_QUERY), $query);
@@ -196,11 +170,11 @@ test('a publication with a TryPost post opens the post details on the insights p
$insightsUrl = route('app.channels.insights', $this->instagram);
$page = visit($insightsUrl);
- waitForChannelInsightsTestId($page, "insights-posts-link-{$this->mostReactions->id}");
+ waitFor($page, "@insights-posts-link-{$this->mostReactions->id}");
$path = $page->script('location.pathname');
$page->click("@insights-posts-link-{$this->mostReactions->id}");
- waitForChannelInsightsTestId($page, "post-details-{$post->id}");
+ waitFor($page, "@post-details-{$post->id}");
$page->assertSeeIn("@post-details-text-{$post->id}", 'Published through TryPost')
->assertScript('location.pathname', $path)
@@ -217,21 +191,15 @@ test('the post details opened from insights copy the link of the sent post', fun
$this->mostReactions->update(['post_id' => $post->id]);
$page = visit(route('app.channels.insights', $this->instagram));
- waitForChannelInsightsTestId($page, "insights-posts-link-{$this->mostReactions->id}");
+ waitFor($page, "@insights-posts-link-{$this->mostReactions->id}");
$page->click("@insights-posts-link-{$this->mostReactions->id}");
- waitForChannelInsightsTestId($page, "post-card-menu-details-{$post->id}");
+ waitFor($page, "@post-card-menu-details-{$post->id}");
$page->script('window.__copied = null; navigator.clipboard.writeText = async (text) => { window.__copied = text; };');
$page->click("@post-card-menu-details-{$post->id}");
- waitForChannelInsightsTestId($page, "post-copy-link-details-{$post->id}");
+ waitFor($page, "@post-copy-link-details-{$post->id}");
$page->click("@post-copy-link-details-{$post->id}");
- $page->script(<<<'JS'
- (async () => {
- for (let i = 0; i < 100 && window.__copied === null; i++) {
- await new Promise((r) => setTimeout(r, 50));
- }
- })();
- JS);
+ waitForCondition($page, 'window.__copied !== null');
expect($page->script('window.__copied'))->toBe('https://www.instagram.com/p/COPY/');
$page->assertNoJavaScriptErrors();
@@ -247,13 +215,13 @@ test('the post details opened from insights share the link of the sent post in a
$this->mostReactions->update(['post_id' => $post->id]);
$page = visit(route('app.channels.insights', $this->instagram));
- waitForChannelInsightsTestId($page, "insights-posts-link-{$this->mostReactions->id}");
+ waitFor($page, "@insights-posts-link-{$this->mostReactions->id}");
$page->click("@insights-posts-link-{$this->mostReactions->id}");
- waitForChannelInsightsTestId($page, "post-card-menu-details-{$post->id}");
+ waitFor($page, "@post-card-menu-details-{$post->id}");
$page->click("@post-card-menu-details-{$post->id}");
- waitForChannelInsightsTestId($page, "post-share-link-details-{$post->id}");
+ waitFor($page, "@post-share-link-details-{$post->id}");
$page->click("@post-share-link-details-{$post->id}");
- waitForChannelInsightsTestId($page, 'post-composer-dialog');
+ waitFor($page, '@post-composer-dialog');
$page->assertSeeIn('@post-composer-dialog', 'https://www.instagram.com/p/SHARE/')
->assertNoJavaScriptErrors();
@@ -269,11 +237,11 @@ test('the post details of a sent post without a link offer no share or copy link
$this->mostReactions->update(['post_id' => $post->id]);
$page = visit(route('app.channels.insights', $this->instagram));
- waitForChannelInsightsTestId($page, "insights-posts-link-{$this->mostReactions->id}");
+ waitFor($page, "@insights-posts-link-{$this->mostReactions->id}");
$page->click("@insights-posts-link-{$this->mostReactions->id}");
- waitForChannelInsightsTestId($page, "post-card-menu-details-{$post->id}");
+ waitFor($page, "@post-card-menu-details-{$post->id}");
$page->click("@post-card-menu-details-{$post->id}");
- waitForChannelInsightsTestId($page, "post-card-menu-content-details-{$post->id}");
+ waitFor($page, "@post-card-menu-content-details-{$post->id}");
$page->assertMissing("@post-share-link-details-{$post->id}")
->assertMissing("@post-copy-link-details-{$post->id}")
@@ -282,17 +250,17 @@ test('the post details of a sent post without a link offer no share or copy link
test('on a phone the channel insights range presets collapse into a dropdown', function () {
$page = visit(route('app.channels.insights', ['account' => $this->instagram]))->resize(390, 844);
- waitForChannelInsightsTestId($page, 'insights-range-mobile-trigger');
+ waitFor($page, '@insights-range-mobile-trigger');
$page->assertScript('document.querySelector("[data-testid=insights-range-7d]").getBoundingClientRect().height', 0)
->assertSeeIn('@insights-range-mobile-trigger', '30 Days')
->click('@insights-range-mobile-trigger');
- waitForChannelInsightsTestId($page, 'insights-range-mobile-30d-check');
+ waitFor($page, '@insights-range-mobile-30d-check');
$page->assertPresent('@insights-range-mobile-30d-check')
->assertMissing('@insights-range-mobile-7d-check')
->click('@insights-range-mobile-7d');
- waitForChannelInsightsScript($page, 'new URLSearchParams(location.search).get("range") === "7d"');
+ waitForQueryParameter($page, 'range', '7d');
$page->assertScript('new URLSearchParams(location.search).get("range")', '7d')
->assertSeeIn('@insights-range-mobile-trigger', '7 Days')
@@ -307,7 +275,7 @@ test('the channel insights header sticks under the channel header with a divider
}
$page = visit(route('app.channels.insights', $this->instagram));
- waitForChannelInsightsTestId($page, 'insights-posts-pagination');
+ waitFor($page, '@insights-posts-pagination');
$page->assertScript('getComputedStyle(document.querySelector("[data-testid=insights-toolbar]")).borderBottomWidth', '1px')
->assertScript('(() => { const scroller = document.querySelector("[data-testid=app-layout-scroller]"); scroller.scrollTop = scroller.scrollHeight; const header = document.querySelector("[data-testid=insights-page-header]"); const toolbar = document.querySelector("[data-testid=insights-toolbar]"); const top = scroller.getBoundingClientRect().top; const stuck = scroller.scrollTop > 0 && Math.abs(header.getBoundingClientRect().top - top) <= 1 && toolbar.getBoundingClientRect().bottom > top; scroller.scrollTop = 0; return stuck; })()', true)
@@ -326,7 +294,7 @@ test('the per post table shows ten posts per page with numbered pages kept in th
}
$page = visit(route('app.channels.insights', $this->instagram));
- waitForChannelInsightsTestId($page, 'insights-posts-pagination');
+ waitFor($page, '@insights-posts-pagination');
$page->assertScript('document.querySelectorAll("#insights-posts-body tr").length', 10)
->assertAttribute('@insights-posts-page-1', 'aria-current', 'page')
@@ -334,7 +302,8 @@ test('the per post table shows ten posts per page with numbered pages kept in th
->assertMissing('@insights-posts-page-3')
->assertAttribute('@insights-posts-page-previous', 'disabled', '')
->click('@insights-posts-page-2');
- waitForChannelInsightsScript($page, 'new URLSearchParams(location.search).get("page") === "2" && document.querySelectorAll("#insights-posts-body tr").length === 3');
+ waitForQueryParameter($page, 'page', '2');
+ waitForCount($page, '#insights-posts-body tr', 3);
$page->assertScript('new URLSearchParams(location.search).get("page")', '2')
->assertScript('document.querySelectorAll("#insights-posts-body tr").length', 3)
@@ -343,11 +312,11 @@ test('the per post table shows ten posts per page with numbered pages kept in th
->assertAttribute('@insights-posts-page-next', 'disabled', '');
$page->refresh();
- waitForChannelInsightsTestId($page, 'insights-posts-pagination');
+ waitFor($page, '@insights-posts-pagination');
$page->assertAttribute('@insights-posts-page-2', 'aria-current', 'page')
->assertScript('document.querySelectorAll("#insights-posts-body tr").length', 3)
->click('@insights-posts-page-previous');
- waitForChannelInsightsScript($page, 'document.querySelectorAll("#insights-posts-body tr").length === 10');
+ waitForCount($page, '#insights-posts-body tr', 10);
$page->assertAttribute('@insights-posts-page-1', 'aria-current', 'page')
->assertNoJavaScriptErrors();
@@ -365,7 +334,7 @@ test('reels, stories and videos show the content type badge with its icon, other
$video->update(['content_type' => PublicationContentType::Video]);
$page = visit(route('app.channels.insights', $this->instagram));
- waitForChannelInsightsTestId($page, "insights-posts-type-{$this->mostReactions->id}");
+ waitFor($page, "@insights-posts-type-{$this->mostReactions->id}");
$page->assertVisible("@insights-posts-type-{$this->mostReactions->id}-icon")
->assertVisible("@insights-posts-type-{$this->mostViews->id}-icon")
@@ -390,7 +359,7 @@ test('the per post table shows the post media from our bucket, a video by its co
$this->mostViews->update(['post_id' => $image->id, 'preview_metadata' => $expired]);
$page = visit(route('app.channels.insights', $this->instagram));
- waitForChannelInsightsTestId($page, "insights-posts-video-{$this->mostReactions->id}");
+ waitFor($page, "@insights-posts-video-{$this->mostReactions->id}");
$page->assertAttribute("@insights-posts-video-{$this->mostReactions->id}", 'src', 'https://cdn.trypost.test/medias/reel.mp4#t=1.5')
->assertScript("document.querySelector('[data-testid=\"insights-posts-row-{$this->mostViews->id}\"] img').getAttribute('src')", 'https://cdn.trypost.test/medias/a.jpg')
diff --git a/tests/Browser/ChannelMediaIssueTest.php b/tests/Browser/ChannelMediaIssueTest.php
index 963a8984c..488da47b7 100644
--- a/tests/Browser/ChannelMediaIssueTest.php
+++ b/tests/Browser/ChannelMediaIssueTest.php
@@ -12,34 +12,11 @@ use App\Models\User;
use App\Models\Workspace;
use Illuminate\Support\Facades\Storage;
-function waitForChannelIssueTestId(mixed $page, string $testId): void
-{
- waitForChannelIssueCondition($page, $testId, 'el.getBoundingClientRect().height > 0');
-}
-
-/**
- * Polls from the page (never sleep(): the test's HTTP server only ticks while
- * Pest awaits Playwright) until the element exists and `$condition` holds.
- */
-function waitForChannelIssueCondition(mixed $page, string $testId, string $condition): void
-{
- $page->script(<<<JS
- (async () => {
- const sel = '[data-testid="{$testId}"]';
- for (let i = 0; i < 100; i++) {
- const el = document.querySelector(sel);
- if (el && ({$condition})) return;
- await new Promise((r) => setTimeout(r, 50));
- }
- })();
- JS);
-}
-
test('an Instagram media warning links to the network limits', function () {
[$post] = seedInstagramFeedImagePost(size: 9 * 1024 * 1024);
$page = visit(route('app.posts.edit', $post));
- waitForChannelIssueTestId($page, 'media-rules-warning');
+ waitFor($page, '@media-rules-warning');
expect($page->script('document.querySelector("[data-testid=media-rules-warning] a")?.href'))
->toBe('https://docs.trypost.it/knowledge-base/media#instagram');
@@ -82,7 +59,7 @@ test('Instagram feed has no global aspect control and asks to adjust unsupported
[$post] = seedInstagramFeedImagePost();
$page = visit(route('app.posts.edit', $post));
- waitForChannelIssueTestId($page, 'post-composer-dialog');
+ waitFor($page, '@post-composer-dialog');
$page->assertMissing('@instagram-aspect-original')
->assertMissing('@instagram-aspect-1-1')
@@ -90,7 +67,7 @@ test('Instagram feed has no global aspect control and asks to adjust unsupported
->assertDisabled('@composer-submit')
->assertVisible('@instagram-edit-image-0');
- waitForChannelIssueTestId($page, 'instagram-feed-media');
+ waitFor($page, '@instagram-feed-media');
$heightToWidth = $page->script('(() => { const frame = document.querySelector("[data-testid=instagram-feed-media]"); const rect = frame.getBoundingClientRect(); return rect.height / rect.width; })()');
expect(abs($heightToWidth - 1600 / 1080))->toBeLessThan(0.01);
@@ -101,7 +78,7 @@ test('Facebook has no aspect ratio selector and accepts an image of any ratio',
[$post] = seedInstagramFeedImagePost(imageMeta: ['width' => $width, 'height' => $height], imageCount: 1, platform: Platform::Facebook);
$page = visit(route('app.posts.edit', $post));
- waitForChannelIssueTestId($page, "composer-account-{$post->social_account_id}");
+ waitFor($page, "@composer-account-{$post->social_account_id}");
expect($page->script('document.querySelectorAll("[data-testid^=facebook-aspect-]").length'))->toBe(0);
@@ -121,21 +98,14 @@ test('saving an Instagram post stores no global aspect ratio', function () {
Storage::put($asset->path, (string) file_get_contents(base_path('tests/fixtures/1x1.png')));
$page = visit(route('app.posts.edit', $post));
- waitForChannelIssueTestId($page, 'composer-save-draft');
+ waitFor($page, '@composer-save-draft');
$page->assertMissing('@instagram-aspect-original')
->assertMissing('@instagram-image-aspect-issue-0')
->click('@composer-save-draft')
->assertNoJavaScriptErrors();
- $page->script(<<<'JS'
- (async () => {
- for (let attempt = 0; attempt < 80; attempt++) {
- if (!document.querySelector('[data-testid="post-composer-dialog"]')) return;
- await new Promise((resolve) => setTimeout(resolve, 100));
- }
- })();
- JS);
+ waitForGone($page, '@post-composer-dialog');
expect($page->script('Boolean(document.querySelector("[data-testid=post-composer-dialog]"))'))->toBeFalse();
expect(data_get($post->fresh()->meta, 'aspect_ratio'))->toBeNull();
@@ -147,7 +117,7 @@ test('Instagram original preview falls back to square when image dimensions are
[$post] = seedInstagramFeedImagePost(imageMeta: []);
$page = visit(route('app.posts.edit', $post));
- waitForChannelIssueTestId($page, 'instagram-feed-media');
+ waitFor($page, '@instagram-feed-media');
$heightToWidth = $page->script('(() => { const frame = document.querySelector("[data-testid=instagram-feed-media]"); const rect = frame.getBoundingClientRect(); return rect.height / rect.width; })()');
@@ -158,7 +128,7 @@ test('supported Instagram original image keeps its own aspect and can publish',
[$post] = seedInstagramFeedImagePost(imageMeta: ['width' => 1080, 'height' => $height]);
$page = visit(route('app.posts.edit', $post));
- waitForChannelIssueTestId($page, 'post-composer-dialog');
+ waitFor($page, '@post-composer-dialog');
$page->assertMissing('@instagram-image-aspect-issue-0')
->assertEnabled('@composer-submit')
@@ -171,7 +141,7 @@ test('Instagram image adjustment offers supported crop presets and clears the or
[$post] = seedInstagramFeedImagePost(imageCount: 1);
$page = visit(route('app.posts.edit', $post));
- waitForChannelIssueTestId($page, 'instagram-edit-image-0');
+ waitFor($page, '@instagram-edit-image-0');
$page->click('@instagram-edit-image-0')
->assertVisible('@crop-aspect-4-5')
@@ -181,15 +151,8 @@ test('Instagram image adjustment offers supported crop presets and clears the or
->click('@crop-aspect-1-1')
->click('@media-editor-apply');
- $page->script(<<<'JS'
- (async () => {
- for (let attempt = 0; attempt < 100; attempt++) {
- if (!document.querySelector('[data-testid="instagram-image-aspect-issue-0"]')
- && !document.querySelector('[data-testid="media-editor-apply"]')) return;
- await new Promise((resolve) => setTimeout(resolve, 100));
- }
- })();
- JS);
+ waitForGone($page, '@instagram-image-aspect-issue-0');
+ waitForGone($page, '@media-editor-apply');
$page->assertMissing('@instagram-image-aspect-issue-0')
->assertEnabled('@composer-submit')
@@ -205,7 +168,7 @@ test('Instagram image editor saves alt text on the selected slide', function ()
Storage::put($asset->path, (string) file_get_contents(base_path('tests/fixtures/1x1.png')));
$page = visit(route('app.posts.edit', $post));
- waitForChannelIssueTestId($page, 'instagram-edit-image-0');
+ waitFor($page, '@instagram-edit-image-0');
$page->click('@instagram-edit-image-0')
->click('@media-editor-alt-tab')
@@ -214,14 +177,7 @@ test('Instagram image editor saves alt text on the selected slide', function ()
->click('@composer-save-draft')
->assertNoJavaScriptErrors();
- $page->script(<<<'JS'
- (async () => {
- for (let attempt = 0; attempt < 80; attempt++) {
- if (!document.querySelector('[data-testid="post-composer-dialog"]')) return;
- await new Promise((resolve) => setTimeout(resolve, 100));
- }
- })();
- JS);
+ waitForGone($page, '@post-composer-dialog');
expect($page->script('Boolean(document.querySelector("[data-testid=post-composer-dialog]"))'))->toBeFalse();
expect(data_get($post->fresh()->media, '0.meta.alt_text'))
@@ -239,7 +195,7 @@ test('appearance filter saves a new image without cropping its original dimensio
$page = visit(route('app.posts.edit', $post));
- waitForChannelIssueTestId($page, "composer-{$post->social_account_id}-edit-0");
+ waitFor($page, "@composer-{$post->social_account_id}-edit-0");
$page->click("@composer-{$post->social_account_id}-edit-0")
->click('@media-editor-appearance-section')
->click('@media-filter-mono');
@@ -254,15 +210,7 @@ test('appearance filter saves a new image without cropping its original dimensio
->assertEnabled('@media-editor-apply')
->click('@media-editor-apply');
- $page->script(<<<'JS'
- (async () => {
- for (let attempt = 0; attempt < 100; attempt++) {
- if (!document.querySelector('[data-testid="media-editor-apply"]')
- && !document.querySelector('[data-testid="composer-save-draft"]')?.disabled) return;
- await new Promise((resolve) => setTimeout(resolve, 100));
- }
- })();
- JS);
+ waitForCondition($page, "!document.querySelector('[data-testid=\"media-editor-apply\"]') && !document.querySelector('[data-testid=\"composer-save-draft\"]')?.disabled");
$newAsset = Media::where('workspace_id', $post->workspace_id)->where('collection', Media::COLLECTION_UPLOADS)->sole();
$image = imagecreatefromstring(Storage::get($newAsset->path));
@@ -290,7 +238,7 @@ test('a media ratio warning names the destination with the same message the serv
$post->update(['content_type' => ContentType::InstagramReel]);
$page = visit(route('app.posts.edit', $post));
- waitForChannelIssueTestId($page, 'media-rules-warning');
+ waitFor($page, '@media-rules-warning');
$message = trans('posts.form.warnings.aspect_ratio_too_wide', [
'destination' => ContentType::InstagramReel->destinationLabel(),
@@ -309,7 +257,7 @@ test('an Instagram feed post without media shows the inline warning once, under
$page = visit(route('app.posts.edit', $post));
$warning = "composer-media-warning-{$post->social_account_id}";
- waitForChannelIssueTestId($page, $warning);
+ waitFor($page, "@{$warning}");
$page->assertSeeIn("@{$warning}", 'Please include an image or video.')
->assertMissing('@media-rules-warning')
diff --git a/tests/Browser/ChannelMetricsCardTest.php b/tests/Browser/ChannelMetricsCardTest.php
index ed1981bc3..82e4f62e1 100644
--- a/tests/Browser/ChannelMetricsCardTest.php
+++ b/tests/Browser/ChannelMetricsCardTest.php
@@ -144,7 +144,9 @@ test('the card shows a skeleton while the series reloads for a new range', funct
}).observe(document.body, { childList: true, subtree: true });
JS);
$page->click('@insights-range-7d');
- waitForCondition($page, 'new URLSearchParams(location.search).get("range") === "7d" && window.__sawMetricsSkeleton && document.querySelector("[data-testid=insights-metrics-chart]")');
+ waitForQueryParameter($page, 'range', '7d');
+ waitForCondition($page, 'window.__sawMetricsSkeleton');
+ waitForState($page, '@insights-metrics-chart', 'true');
$page->assertScript('window.__sawMetricsSkeleton', true)
->assertVisible('@insights-metrics-chart')
@@ -213,7 +215,11 @@ test('presets swap the chart series and the selected preset and period survive a
$page->click('@insights-post-type-filter');
waitFor($page, '@insights-post-type-option-instagram_reel');
$page->click('@insights-post-type-option-instagram_reel');
- waitForCondition($page, 'new URLSearchParams(location.search).getAll("types[]").includes("instagram_reel") && document.querySelector("[data-testid=insights-metrics-chart]") && document.querySelector("[data-testid=insights-preset-audience_growth]")?.getAttribute("aria-pressed") === "true" && document.querySelector("[data-testid=insights-metrics-mode-both]")?.getAttribute("aria-pressed") === "true" && document.querySelector("[data-testid=insights-metrics-legend-net_followers-previous]")');
+ waitForCondition($page, 'new URLSearchParams(location.search).getAll("types[]").includes("instagram_reel")');
+ waitForState($page, '@insights-metrics-chart', 'true');
+ waitForState($page, '@insights-preset-audience_growth', "element.getAttribute('aria-pressed') === 'true'");
+ waitForState($page, '@insights-metrics-mode-both', "element.getAttribute('aria-pressed') === 'true'");
+ waitForState($page, '@insights-metrics-legend-net_followers-previous', 'true');
$page->assertScript('decodeURIComponent(location.search).includes("instagram_reel")', true)
->assertAttribute('@insights-preset-audience_growth', 'aria-pressed', 'true')
@@ -253,7 +259,7 @@ test('the mode toggle shows the comparison period and both periods', function ()
->assertAttribute('@insights-metrics-mode-both', 'aria-pressed', 'true')
->assertScript('document.querySelectorAll("[data-testid=insights-metrics-bar]").length > 0', true)
->click('@insights-metrics-mode-previous');
- waitForCondition($page, 'document.querySelector("[data-testid=insights-metrics-legend-posts-value]")?.textContent.trim() === "1"');
+ waitForState($page, '@insights-metrics-legend-posts-value', "element.textContent.trim() === '1'");
$page->assertSeeIn('@insights-metrics-legend-posts-value', '1')
->assertMissing('@insights-metrics-legend-posts-previous')
@@ -268,24 +274,24 @@ test('the insight banner reads the selected chart against the previous period',
$page->assertAttribute('@insights-metrics-insight', 'data-insight', 'content_impact.down')
->assertSeeIn('@insights-metrics-insight', 'Your content impact dropped this period.')
->click('@insights-metric-primary');
- waitForCondition($page, 'document.querySelector("[data-testid=insights-metrics-insight]")?.dataset.insight === "posts.up"');
+ waitForState($page, '@insights-metrics-insight', "element.dataset.insight === 'posts.up'");
$page->assertSeeIn('@insights-metrics-insight', 'You posted more than last period.')
->click('@insights-preset-audience_growth');
- waitForCondition($page, 'document.querySelector("[data-testid=insights-metrics-insight]")?.dataset.insight === "audience.up"');
+ waitForState($page, '@insights-metrics-insight', "element.dataset.insight === 'audience.up'");
$page->assertSeeIn('@insights-metrics-insight', 'Your audience grew this period.')
->assertMissing('@insights-metrics-post-totals-note')
->click('@insights-metrics-mode-previous');
- waitForCondition($page, 'document.querySelector("[data-testid=insights-metrics-mode-previous]")?.getAttribute("aria-pressed") === "true"');
+ waitForState($page, '@insights-metrics-mode-previous', "element.getAttribute('aria-pressed') === 'true'");
$page->assertAttribute('@insights-metrics-insight', 'data-insight', 'audience.up')
->click('@insights-metrics-mode-both');
- waitForCondition($page, 'document.querySelector("[data-testid=insights-metrics-insight]")?.dataset.insight.startsWith("audience_compared")');
+ waitForState($page, '@insights-metrics-insight', "element.dataset.insight.startsWith('audience_compared')");
$page->assertSeeIn('@insights-metrics-insight', 'Your audience grew')
->click('@insights-preset-visibility');
- waitForCondition($page, 'document.querySelector("[data-testid=insights-metrics-insight]")?.dataset.insight === "visibility.up"');
+ waitForState($page, '@insights-metrics-insight', "element.dataset.insight === 'visibility.up'");
$page->assertSeeIn('@insights-metrics-insight', 'More people discovered you than last period.')
->assertNoJavaScriptErrors();
@@ -324,7 +330,7 @@ test('the column chooser hides and adds columns and remembers the choice', funct
$page->assertMissing('@insights-column-impressions')
->click('@insights-column-views');
- waitForCondition($page, '!document.querySelector("[data-testid=insights-sort-views]")');
+ waitForGone($page, '@insights-sort-views');
$page->click('@insights-column-watch_time_minutes');
waitFor($page, '@insights-column-head-watch_time_minutes');
diff --git a/tests/Browser/ChannelPostingGoalTest.php b/tests/Browser/ChannelPostingGoalTest.php
index e5d1fae8f..05a7cb54f 100644
--- a/tests/Browser/ChannelPostingGoalTest.php
+++ b/tests/Browser/ChannelPostingGoalTest.php
@@ -10,17 +10,7 @@ use Illuminate\Support\Facades\Http;
function waitForPostingGoalTestId(mixed $page, string $testId): void
{
- $page->script(<<<JS
- (async () => {
- const sel = '[data-testid="{$testId}"]';
- for (let i = 0; i < 100; i++) {
- const el = document.querySelector(sel);
- if (el && el.getBoundingClientRect().height > 0) return;
- await new Promise((r) => setTimeout(r, 50));
- }
- })();
- JS);
-
+ waitFor($page, "@{$testId}");
waitForWebFonts($page);
}
@@ -51,13 +41,6 @@ function postingGoalTestIdAppearsWithin(mixed $page, string $testId, int $attemp
return postingGoalPollFor($page, "document.querySelector({$selector}) !== null", $attempts);
}
-function waitForPostingGoalTestIdGone(mixed $page, string $testId, int $attempts = 120): void
-{
- $selector = json_encode(postingGoalTestIdSelector($testId));
-
- postingGoalPollFor($page, "document.querySelector({$selector}) === null", $attempts);
-}
-
function waitForPostingGoalViewportSettled(mixed $page, int $width, string $testId): bool
{
$selector = json_encode(postingGoalTestIdSelector($testId));
@@ -315,7 +298,7 @@ test('the recommended-time help opens above its trigger and links to the docs',
->assertAttributeContains('@goal-help-learn-more', 'rel', 'noopener');
$page->click('@goal-help-close');
- waitForPostingGoalTestIdGone($page, 'goal-help-popover');
+ waitForGone($page, '@goal-help-popover');
$page->assertNotPresent('@goal-help-popover');
$page->assertVisible('@goal-flow')->assertNoJavaScriptErrors();
@@ -355,7 +338,7 @@ test('connecting a channel fires a confetti burst that cleans up after itself',
waitForPostingGoalTestId($page, 'confetti-canvas');
$page->assertPresent('@confetti-canvas');
- waitForPostingGoalTestIdGone($page, 'confetti-canvas', 200);
+ waitForGone($page, '@confetti-canvas');
$page->assertNotPresent('@confetti-canvas');
$page->assertVisible('@goal-flow')->assertNoJavaScriptErrors();
diff --git a/tests/Browser/ChannelReorderTest.php b/tests/Browser/ChannelReorderTest.php
index 4e1025951..6007aa3e9 100644
--- a/tests/Browser/ChannelReorderTest.php
+++ b/tests/Browser/ChannelReorderTest.php
@@ -6,27 +6,6 @@ use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
-function waitForChannelReorderTestId(mixed $page, string $testId): void
-{
- $page->script(<<<JS
- (async () => {
- const sel = '[data-testid="{$testId}"]';
- for (let i = 0; i < 100; i++) {
- const el = document.querySelector(sel);
- if (el && el.getBoundingClientRect().height > 0) return;
- await new Promise((r) => setTimeout(r, 50));
- }
- })();
- JS);
-}
-
-function waitForChannelReorderDatabase(mixed $page, Closure $condition): void
-{
- for ($attempt = 0; $attempt < 50 && ! $condition(); $attempt++) {
- $page->script('new Promise((resolve) => setTimeout(resolve, 100))');
- }
-}
-
/**
* @return array{0: User, 1: list<SocialAccount>}
*/
@@ -72,9 +51,9 @@ test('the channels settings page lists channels without reordering them', functi
$this->actingAs($user);
$page = visit(route('app.workspace.channels'));
- waitForChannelReorderTestId($page, "channel-list-row-{$third->id}");
+ waitFor($page, "@channel-list-row-{$third->id}");
$page->click("@channel-menu-{$second->id}");
- waitForChannelReorderTestId($page, "channel-disconnect-{$second->id}");
+ waitFor($page, "@channel-disconnect-{$second->id}");
expect($page->script('document.querySelectorAll(\'[data-testid^="channel-handle-"], [data-testid^="channel-menu-move-"], [data-sortable-channel]\').length'))->toBe(0)
->and(channelReorderDomOrder($page, 'channel-list-row-', [$first, $second, $third]))->toBe([$first->id, $second->id, $third->id]);
@@ -86,10 +65,10 @@ test('a sidebar channel can be moved with the keyboard', function () {
$this->actingAs($user);
$page = visit(route('app.posts.index'));
- waitForChannelReorderTestId($page, "sidebar-channel-row-{$third->id}");
+ waitFor($page, "@sidebar-channel-row-{$third->id}");
$page->hover("@sidebar-channel-row-{$third->id}");
$page->keys("@sidebar-channel-handle-{$third->id}", 'ArrowUp');
- waitForChannelReorderDatabase($page, fn (): bool => $third->refresh()->position === 1);
+ waitForDatabase($page, fn (): bool => $third->refresh()->position === 1);
expect($user->currentWorkspace->socialAccounts()->pluck('id')->all())->toBe([$first->id, $third->id, $second->id])
->and($page->script('document.activeElement?.dataset.testid'))->toBe("sidebar-channel-handle-{$third->id}")
@@ -102,14 +81,14 @@ test('a stale reorder is rolled back and reported', function () {
$this->actingAs($user);
$page = visit(route('app.posts.index'));
- waitForChannelReorderTestId($page, "sidebar-channel-row-{$second->id}");
+ waitFor($page, "@sidebar-channel-row-{$second->id}");
$late = SocialAccount::factory()->x()->create(['workspace_id' => $user->current_workspace_id]);
$page->hover("@sidebar-channel-row-{$second->id}");
$page->keys("@sidebar-channel-handle-{$second->id}", 'ArrowUp');
- waitForChannelReorderTestId($page, 'channels-reorder-error-toast');
+ waitFor($page, '@channels-reorder-error-toast');
$page->assertSeeIn('@channels-reorder-error-toast', __('channels.reorder.stale'));
- waitForChannelReorderTestId($page, "sidebar-channel-row-{$late->id}");
+ waitFor($page, "@sidebar-channel-row-{$late->id}");
expect($user->currentWorkspace->socialAccounts()->pluck('id')->all())->toBe([$first->id, $second->id, $third->id, $late->id])
->and(channelReorderDomOrder($page, 'sidebar-channel-row-', [$first, $second, $third, $late]))->toBe([$first->id, $second->id, $third->id, $late->id]);
diff --git a/tests/Browser/ChannelSettingsPageTest.php b/tests/Browser/ChannelSettingsPageTest.php
index 6fc7226ce..c7f09c5a5 100644
--- a/tests/Browser/ChannelSettingsPageTest.php
+++ b/tests/Browser/ChannelSettingsPageTest.php
@@ -14,20 +14,6 @@ use App\Models\User;
use App\Models\Workspace;
use App\Support\PostingSchedule;
-function waitForChannelSettingsPageTestId(mixed $page, string $testId): void
-{
- $page->script(<<<JS
- (async () => {
- const sel = '[data-testid="{$testId}"]';
- for (let i = 0; i < 100; i++) {
- const el = document.querySelector(sel);
- if (el && el.getBoundingClientRect().height > 0) return;
- await new Promise((r) => setTimeout(r, 50));
- }
- })();
- JS);
-}
-
function channelSettingsPageSetup(?PostingSchedule $schedule = null): array
{
$user = User::factory()->create();
@@ -46,28 +32,23 @@ function channelSettingsPageSetup(?PostingSchedule $schedule = null): array
function pickChannelSettingsOption(mixed $page, string $select, string $value): void
{
$page->click("@{$select}");
- waitForChannelSettingsPageTestId($page, "{$select}-option-{$value}");
+ waitFor($page, "@{$select}-option-{$value}");
$page->click("@{$select}-option-{$value}");
}
function chooseChannelSettingsTimezone(mixed $page, string $search, string $optionKey): void
{
- waitForChannelSettingsPageTestId($page, 'channel-timezone-trigger');
+ waitFor($page, '@channel-timezone-trigger');
$page->click('@channel-timezone-trigger');
- waitForChannelSettingsPageTestId($page, 'channel-timezone-search');
+ waitFor($page, '@channel-timezone-search');
$page->type('@channel-timezone-search', $search);
- waitForChannelSettingsPageTestId($page, "channel-timezone-option-{$optionKey}");
+ waitFor($page, "@channel-timezone-option-{$optionKey}");
$page->click("@channel-timezone-option-{$optionKey}");
}
function waitForChannelSaved(mixed $page, SocialAccount $channel, callable $predicate): void
{
- for ($i = 0; $i < 40; $i++) {
- if ($predicate($channel->fresh())) {
- return;
- }
- $page->script('new Promise((r) => setTimeout(r, 100))');
- }
+ waitForDatabase($page, fn (): bool => $predicate($channel->fresh()));
}
test('adding a weekday time, removing one and toggling a day persist', function () {
@@ -75,13 +56,13 @@ test('adding a weekday time, removing one and toggling a day persist', function
$this->actingAs($user);
$page = visit(route('app.channels.settings', $channel));
- waitForChannelSettingsPageTestId($page, 'schedule-day-1-time-0942');
+ waitFor($page, '@schedule-day-1-time-0942');
pickChannelSettingsOption($page, 'schedule-add-target', 'weekdays');
pickChannelSettingsOption($page, 'schedule-add-hour', '18');
pickChannelSettingsOption($page, 'schedule-add-minute', '30');
$page->click('@schedule-add-submit');
- waitForChannelSettingsPageTestId($page, 'schedule-day-5-time-1830');
+ waitFor($page, '@schedule-day-5-time-1830');
waitForChannelSaved($page, $channel, fn (SocialAccount $c): bool => $c->posting_schedule->slotCount() === 6);
$page->click('@schedule-day-1-time-0942-remove');
@@ -104,7 +85,7 @@ test('the time zone and goal save from the page', function () {
$page = visit(route('app.channels.settings', $channel));
chooseChannelSettingsTimezone($page, 'Warsaw', 'Europe-Warsaw');
- waitForChannelSettingsPageTestId($page, 'channel-timezone-confirm-submit');
+ waitFor($page, '@channel-timezone-confirm-submit');
$page->click('@channel-timezone-confirm-submit');
waitForChannelSaved($page, $channel, fn (SocialAccount $c): bool => $c->timezone === 'Europe/Warsaw');
@@ -126,25 +107,25 @@ test('clear all, generate from goal and copy from another channel', function ()
$this->actingAs($user);
$page = visit(route('app.channels.settings', $channel));
- waitForChannelSettingsPageTestId($page, 'schedule-clear');
+ waitFor($page, '@schedule-clear');
$page->click('@schedule-clear');
- waitForChannelSettingsPageTestId($page, 'schedule-clear-confirm');
+ waitFor($page, '@schedule-clear-confirm');
$page->click('@schedule-clear-confirm');
waitForChannelSaved($page, $channel, fn (SocialAccount $c): bool => $c->posting_schedule->slotCount() === 0);
$page->click('@schedule-generate');
- waitForChannelSettingsPageTestId($page, 'schedule-generate-goal');
+ waitFor($page, '@schedule-generate-goal');
$page->click('@schedule-generate-goal');
- waitForChannelSettingsPageTestId($page, 'schedule-generate-confirm');
+ waitFor($page, '@schedule-generate-confirm');
$page->click('@schedule-generate-confirm');
waitForChannelSaved($page, $channel, fn (SocialAccount $c): bool => $c->posting_schedule->slotCount() === 3);
$page->click('@schedule-generate');
- waitForChannelSettingsPageTestId($page, 'schedule-generate-copy');
+ waitFor($page, '@schedule-generate-copy');
$page->click('@schedule-generate-copy');
- waitForChannelSettingsPageTestId($page, "schedule-generate-copy-{$other->id}");
+ waitFor($page, "@schedule-generate-copy-{$other->id}");
$page->click("@schedule-generate-copy-{$other->id}");
- waitForChannelSettingsPageTestId($page, 'schedule-generate-confirm');
+ waitFor($page, '@schedule-generate-confirm');
$page->click('@schedule-generate-confirm');
waitForChannelSaved($page, $channel, fn (SocialAccount $c): bool => $c->posting_schedule->days()[6]['times'] === ['17:08']);
@@ -165,29 +146,22 @@ test('the copy from channel search filters the list and a pick asks to confirm',
$this->actingAs($user);
$page = visit(route('app.channels.settings', $channel));
- waitForChannelSettingsPageTestId($page, 'schedule-generate');
+ waitFor($page, '@schedule-generate');
$page->click('@schedule-generate');
- waitForChannelSettingsPageTestId($page, 'schedule-generate-copy');
+ waitFor($page, '@schedule-generate-copy');
$page->click('@schedule-generate-copy');
- waitForChannelSettingsPageTestId($page, 'schedule-generate-copy-search');
+ waitFor($page, '@schedule-generate-copy-search');
$page->assertVisible("@schedule-generate-copy-{$x->id}")
->assertVisible("@schedule-generate-copy-{$bluesky->id}");
$page->type('@schedule-generate-copy-search', 'Bluesky');
- $page->script(<<<JS
- (async () => {
- for (let i = 0; i < 100; i++) {
- if (!document.querySelector('[data-testid="schedule-generate-copy-{$x->id}"]')) return;
- await new Promise((r) => setTimeout(r, 50));
- }
- })();
- JS);
+ waitForGone($page, "@schedule-generate-copy-{$x->id}");
$page->assertMissing("@schedule-generate-copy-{$x->id}")
->assertVisible("@schedule-generate-copy-{$bluesky->id}");
$page->click("@schedule-generate-copy-{$bluesky->id}");
- waitForChannelSettingsPageTestId($page, 'schedule-generate-confirm');
+ waitFor($page, '@schedule-generate-confirm');
$page->assertVisible('@schedule-generate-confirm')
->assertNoJavaScriptErrors();
});
@@ -199,9 +173,9 @@ test('a fifth time on a day is blocked', function () {
$this->actingAs($user);
$page = visit(route('app.channels.settings', $channel));
- waitForChannelSettingsPageTestId($page, 'schedule-add-target');
+ waitFor($page, '@schedule-add-target');
pickChannelSettingsOption($page, 'schedule-add-target', '2');
- waitForChannelSettingsPageTestId($page, 'schedule-add-limit');
+ waitFor($page, '@schedule-add-limit');
$page->assertVisible('@schedule-add-limit')->assertMissing('@schedule-add-submit');
expect($channel->fresh()->posting_schedule->days()[2]['times'])->toHaveCount(4);
@@ -214,7 +188,7 @@ test('a channel without a schedule shows the empty state', function () {
$this->actingAs($user);
$page = visit(route('app.channels.settings', $channel));
- waitForChannelSettingsPageTestId($page, 'schedule-empty');
+ waitFor($page, '@schedule-empty');
$page->assertVisible('@schedule-empty')->assertVisible('@schedule-generate')->assertNoJavaScriptErrors();
});
@@ -226,7 +200,7 @@ test('two rapid removes on different days both persist', function () {
$this->actingAs($user);
$page = visit(route('app.channels.settings', $channel));
- waitForChannelSettingsPageTestId($page, 'schedule-day-1-time-0900-remove');
+ waitFor($page, '@schedule-day-1-time-0900-remove');
$page->click('@schedule-day-1-time-0900-remove')->click('@schedule-day-2-time-1000-remove');
waitForChannelSaved($page, $channel, fn (SocialAccount $c): bool => $c->posting_schedule->slotCount() === 1);
$page->script('new Promise((r) => setTimeout(r, 500))');
@@ -244,9 +218,9 @@ test('meet my posting goal is disabled with a hint once the goal is met', functi
$this->actingAs($user);
$page = visit(route('app.channels.settings', $channel));
- waitForChannelSettingsPageTestId($page, 'schedule-generate');
+ waitFor($page, '@schedule-generate');
$page->click('@schedule-generate');
- waitForChannelSettingsPageTestId($page, 'schedule-generate-goal');
+ waitFor($page, '@schedule-generate-goal');
$page->assertAttribute('@schedule-generate-goal', 'data-disabled', '')
->assertAttribute('@schedule-generate-copy', 'data-disabled', '')
@@ -256,7 +230,7 @@ test('meet my posting goal is disabled with a hint once the goal is met', functi
$page->assertScript('(() => { const toggle = document.querySelector("[data-testid=schedule-day-1-toggle]"); const label = toggle.parentElement.querySelector("span").getBoundingClientRect(); const box = toggle.getBoundingClientRect(); return Math.abs((label.top + label.height / 2) - (box.top + box.height / 2)) <= 1 && label.height < 20; })()', true);
$page->hover('@schedule-generate-goal-hint');
- waitForChannelSettingsPageTestId($page, 'schedule-generate-goal-tooltip');
+ waitFor($page, '@schedule-generate-goal-tooltip');
$page->assertVisible('@schedule-generate-goal-tooltip')
->assertMissing('@schedule-generate-confirm');
@@ -270,7 +244,7 @@ test('the schedule grid follows the week start and the 12-hour clock', function
$this->actingAs($user);
$page = visit(route('app.channels.settings', $channel));
- waitForChannelSettingsPageTestId($page, 'schedule-day-0-time-1430-meridiem');
+ waitFor($page, '@schedule-day-0-time-1430-meridiem');
$page->assertScript("document.querySelector('[data-testid^=\"schedule-day-\"]').dataset.testid", 'schedule-day-0')
->assertSeeIn('@schedule-day-0-time-1430-hour', '2')
@@ -283,9 +257,9 @@ test('the channel time zone picker suggests the browser time zone first', functi
$this->actingAs($user);
$page = visit(route('app.channels.settings', $channel));
- waitForChannelSettingsPageTestId($page, 'channel-timezone-trigger');
+ waitFor($page, '@channel-timezone-trigger');
$page->click('@channel-timezone-trigger');
- waitForChannelSettingsPageTestId($page, 'channel-timezone-detected');
+ waitFor($page, '@channel-timezone-detected');
$page->assertVisible('@channel-timezone-detected')->assertNoJavaScriptErrors();
});
@@ -296,21 +270,21 @@ test('changing the time zone asks first and cancel and escape keep the old zone'
$page = visit(route('app.channels.settings', $channel));
chooseChannelSettingsTimezone($page, 'Warsaw', 'Europe-Warsaw');
- waitForChannelSettingsPageTestId($page, 'channel-timezone-confirm-dialog');
+ waitFor($page, '@channel-timezone-confirm-dialog');
$order = $page->script('[...document.querySelectorAll(\'[data-testid="channel-timezone-confirm-dialog"] button[data-testid]\')].map((button) => button.dataset.testid)');
expect($order)->toBe(['channel-timezone-confirm-cancel', 'channel-timezone-confirm-submit']);
$page->assertSeeIn('@channel-timezone-confirm-dialog', 'Europe/Warsaw')
->click('@channel-timezone-confirm-cancel');
- $page->script('(async () => { for (let i = 0; i < 100; i++) { if (!document.querySelector(\'[data-testid="channel-timezone-confirm-dialog"]\')) return; await new Promise((r) => setTimeout(r, 50)); } })();');
+ waitForGone($page, '@channel-timezone-confirm-dialog');
$page->assertSeeIn('@channel-timezone-trigger', 'UTC');
expect($channel->fresh()->timezone)->toBe('UTC');
chooseChannelSettingsTimezone($page, 'Warsaw', 'Europe-Warsaw');
- waitForChannelSettingsPageTestId($page, 'channel-timezone-confirm-cancel');
+ waitFor($page, '@channel-timezone-confirm-cancel');
$page->keys('@channel-timezone-confirm-cancel', 'Escape');
- $page->script('(async () => { for (let i = 0; i < 100; i++) { if (!document.querySelector(\'[data-testid="channel-timezone-confirm-dialog"]\')) return; await new Promise((r) => setTimeout(r, 50)); } })();');
+ waitForGone($page, '@channel-timezone-confirm-dialog');
$page->assertMissing('@channel-timezone-confirm-dialog');
expect($channel->fresh()->timezone)->toBe('UTC');
@@ -330,13 +304,11 @@ test('confirming the time zone saves it and reflows the queue into the new zone
$page = visit(route('app.channels.settings', $channel));
chooseChannelSettingsTimezone($page, 'Warsaw', 'Europe-Warsaw');
- waitForChannelSettingsPageTestId($page, 'channel-timezone-confirm-submit');
+ waitFor($page, '@channel-timezone-confirm-submit');
$page->click('@channel-timezone-confirm-submit');
waitForChannelSaved($page, $channel, fn (SocialAccount $c): bool => $c->timezone === 'Europe/Warsaw');
- for ($i = 0; $i < 40 && $post->fresh()->scheduled_at->setTimezone('Europe/Warsaw')->format('H:i') !== '09:42'; $i++) {
- $page->script('new Promise((r) => setTimeout(r, 100))');
- }
+ waitForDatabase($page, fn (): bool => $post->fresh()->scheduled_at->setTimezone('Europe/Warsaw')->format('H:i') === '09:42');
$local = $post->fresh()->scheduled_at->setTimezone('Europe/Warsaw');
expect($local->format('H:i'))->toBe('09:42')
@@ -350,7 +322,7 @@ test('on a phone the schedule stacks one day per row in week-start order without
$this->actingAs($user);
$page = visit(route('app.channels.settings', $channel))->resize(390, 844);
- waitForChannelSettingsPageTestId($page, 'schedule-day-1-time-0942');
+ waitFor($page, '@schedule-day-1-time-0942');
$page->assertScript(<<<'JS'
(() => {
@@ -373,13 +345,13 @@ test('on a phone toggling a day, adding and removing a time persist', function (
$this->actingAs($user);
$page = visit(route('app.channels.settings', $channel))->resize(390, 844);
- waitForChannelSettingsPageTestId($page, 'schedule-day-1-time-0942');
+ waitFor($page, '@schedule-day-1-time-0942');
pickChannelSettingsOption($page, 'schedule-add-target', 'weekdays');
pickChannelSettingsOption($page, 'schedule-add-hour', '18');
pickChannelSettingsOption($page, 'schedule-add-minute', '30');
$page->click('@schedule-add-submit');
- waitForChannelSettingsPageTestId($page, 'schedule-day-5-time-1830');
+ waitFor($page, '@schedule-day-5-time-1830');
waitForChannelSaved($page, $channel, fn (SocialAccount $c): bool => $c->posting_schedule->slotCount() === 6);
$page->click('@schedule-day-1-time-0942-remove');
diff --git a/tests/Browser/ChannelsSettingsTest.php b/tests/Browser/ChannelsSettingsTest.php
index deccd1e46..17ac64fa9 100644
--- a/tests/Browser/ChannelsSettingsTest.php
+++ b/tests/Browser/ChannelsSettingsTest.php
@@ -7,20 +7,6 @@ use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
-function waitForChannelsSettingsTestId(mixed $page, string $testId): void
-{
- $page->script(<<<JS
- (async () => {
- const sel = '[data-testid="{$testId}"]';
- for (let i = 0; i < 100; i++) {
- const el = document.querySelector(sel);
- if (el && el.getBoundingClientRect().height > 0) return;
- await new Promise((r) => setTimeout(r, 50));
- }
- })();
- JS);
-}
-
function channelsSettingsAdmin(): User
{
$user = User::factory()->create();
@@ -40,11 +26,11 @@ test('channels are listed one per row with settings and actions', function () {
$this->actingAs($user);
$page = visit(route('app.workspace.channels'));
- waitForChannelsSettingsTestId($page, "channel-row-{$channel->id}");
+ waitFor($page, "@channel-row-{$channel->id}");
$page->assertVisible("@channel-settings-{$channel->id}")
->click("@channel-menu-{$channel->id}");
- waitForChannelsSettingsTestId($page, "channel-disconnect-{$channel->id}");
+ waitFor($page, "@channel-disconnect-{$channel->id}");
$page->assertMissing("@channel-toggle-{$channel->id}")
->assertSeeIn("@channel-menu-reconnect-{$channel->id}", __('channels.refresh_connection'))
@@ -60,10 +46,10 @@ test('disconnecting a channel asks for the translated disconnect keyword, not th
$keyword = __('channels.disconnect_modal.keyword');
$page = visit(route('app.workspace.channels'));
- waitForChannelsSettingsTestId($page, "channel-row-{$channel->id}");
+ waitFor($page, "@channel-row-{$channel->id}");
$page->click("@channel-menu-{$channel->id}");
- waitForChannelsSettingsTestId($page, "channel-disconnect-{$channel->id}");
+ waitFor($page, "@channel-disconnect-{$channel->id}");
$page->click("@channel-disconnect-{$channel->id}")
->assertVisible('@confirm-delete-modal')
@@ -87,7 +73,7 @@ test('an empty workspace shows only the centered illustration with a connect but
$this->actingAs(channelsSettingsAdmin());
$page = visit(route('app.workspace.channels'));
- waitForChannelsSettingsTestId($page, 'channels-empty');
+ waitFor($page, '@channels-empty');
$page->assertVisible('@channels-empty-illustration')
->assertSeeIn('@channels-empty', __('channels.empty'))
@@ -104,7 +90,7 @@ test('an empty workspace shows only the centered illustration with a connect but
JS))->toBeTrue();
$page->click('@channels-empty-connect');
- waitForChannelsSettingsTestId($page, 'connect-channel-dialog');
+ waitFor($page, '@connect-channel-dialog');
$page->assertVisible('@connect-channel-dialog')->assertNoJavaScriptErrors();
});
@@ -116,7 +102,7 @@ test('a channel with a lost connection shows the disconnected dot in the list an
$this->actingAs($user);
$page = visit(route('app.workspace.channels'));
- waitForChannelsSettingsTestId($page, "channel-row-{$lost->id}");
+ waitFor($page, "@channel-row-{$lost->id}");
$page->assertVisible("@channel-avatar-disconnected-{$lost->id}")
->assertMissing("@channel-avatar-disconnected-{$healthy->id}")
@@ -127,7 +113,7 @@ test('a channel with a lost connection shows the disconnected dot in the list an
->assertNoJavaScriptErrors();
$page = visit(route('app.channels.publish', $lost));
- waitForChannelsSettingsTestId($page, 'header-title');
+ waitFor($page, '@header-title');
$page->assertVisible("@channel-avatar-disconnected-{$lost->id}")->assertNoJavaScriptErrors();
});
@@ -138,13 +124,13 @@ test('refresh connection in the disconnect dialog closes it instead of disconnec
$this->actingAs($user);
$page = visit(route('app.workspace.channels'));
- waitForChannelsSettingsTestId($page, "channel-row-{$channel->id}");
+ waitFor($page, "@channel-row-{$channel->id}");
$page->click("@channel-menu-{$channel->id}");
- waitForChannelsSettingsTestId($page, "channel-disconnect-{$channel->id}");
+ waitFor($page, "@channel-disconnect-{$channel->id}");
$page->click("@channel-disconnect-{$channel->id}");
- waitForChannelsSettingsTestId($page, 'disconnect-channel-refresh');
+ waitFor($page, '@disconnect-channel-refresh');
$page->click('@disconnect-channel-refresh')
->assertMissing('@confirm-delete-modal')
@@ -161,11 +147,11 @@ test('the disconnect dialog shows the keyword with a copy button, like the other
$keyword = __('channels.disconnect_modal.keyword');
$page = visit(route('app.workspace.channels'));
- waitForChannelsSettingsTestId($page, "channel-row-{$channel->id}");
+ waitFor($page, "@channel-row-{$channel->id}");
$page->click("@channel-menu-{$channel->id}");
- waitForChannelsSettingsTestId($page, "channel-disconnect-{$channel->id}");
+ waitFor($page, "@channel-disconnect-{$channel->id}");
$page->click("@channel-disconnect-{$channel->id}");
- waitForChannelsSettingsTestId($page, 'confirm-delete-copy-keyword');
+ waitFor($page, '@confirm-delete-copy-keyword');
$page->assertSeeIn('@confirm-delete-modal', __('common.confirm_modal.type'))
->assertSeeIn('@confirm-delete-modal', __('common.confirm_modal.to_confirm'))
@@ -188,17 +174,17 @@ test('an instagram login channel offers to link a facebook page, which reconnect
$this->actingAs($user);
$page = visit(route('app.workspace.channels'));
- waitForChannelsSettingsTestId($page, "channel-row-{$viaFacebook->id}");
+ waitFor($page, "@channel-row-{$viaFacebook->id}");
$page->click("@channel-menu-{$viaFacebook->id}");
- waitForChannelsSettingsTestId($page, "channel-menu-reconnect-{$viaFacebook->id}");
+ waitFor($page, "@channel-menu-reconnect-{$viaFacebook->id}");
$page->assertMissing("@channel-menu-link-facebook-{$viaFacebook->id}")
->keys("@channel-menu-reconnect-{$viaFacebook->id}", 'Escape');
$page->click("@channel-menu-{$instagram->id}");
- waitForChannelsSettingsTestId($page, "channel-menu-link-facebook-{$instagram->id}");
+ waitFor($page, "@channel-menu-link-facebook-{$instagram->id}");
$page->assertSeeIn("@channel-menu-link-facebook-{$instagram->id}", __('channels.link_facebook_page'))
->click("@channel-menu-link-facebook-{$instagram->id}");
- waitForChannelsSettingsTestId($page, 'instagram-facebook-requirements');
+ waitFor($page, '@instagram-facebook-requirements');
$page->script(<<<'JS'
document.addEventListener('inertia:before', (event) => {
@@ -207,7 +193,7 @@ test('an instagram login channel offers to link a facebook page, which reconnect
});
JS);
$page->click('@instagram-facebook-requirements-connect');
- $page->script('(async () => { for (let i = 0; i < 100 && window.__connectUrl === undefined; i++) await new Promise((r) => setTimeout(r, 50)); })()');
+ waitForCondition($page, 'window.__connectUrl !== undefined');
expect($page->script('window.__connectUrl'))->toContain("reconnect={$instagram->id}")
->and($page->script('new URL(window.__connectUrl).pathname'))->toBe((string) parse_url(route('app.social.instagram-facebook.connect'), PHP_URL_PATH));
diff --git a/tests/Browser/CommandPaletteTest.php b/tests/Browser/CommandPaletteTest.php
index 6ed091317..bcfbe043d 100644
--- a/tests/Browser/CommandPaletteTest.php
+++ b/tests/Browser/CommandPaletteTest.php
@@ -6,45 +6,6 @@ use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
-function waitForCommandPaletteTestId(mixed $page, string $testId): void
-{
- $page->script(<<<JS
- (async () => {
- const sel = '[data-testid="{$testId}"]';
- for (let i = 0; i < 100; i++) {
- const el = document.querySelector(sel);
- if (el && el.getBoundingClientRect().height > 0) return;
- await new Promise((r) => setTimeout(r, 50));
- }
- })();
- JS);
-}
-
-function waitForCommandPaletteGone(mixed $page, string $testId): void
-{
- $page->script(<<<JS
- (async () => {
- const sel = '[data-testid="{$testId}"]';
- for (let i = 0; i < 100; i++) {
- if (!document.querySelector(sel)) return;
- await new Promise((r) => setTimeout(r, 50));
- }
- })();
- JS);
-}
-
-function waitForCommandPalettePath(mixed $page, string $path): void
-{
- $page->script(<<<JS
- (async () => {
- for (let i = 0; i < 100; i++) {
- if (window.location.pathname === '{$path}' && document.querySelector('[data-testid="publish-page"]')) return;
- await new Promise((r) => setTimeout(r, 50));
- }
- })();
- JS);
-}
-
function commandPaletteUser(string $role): User
{
$owner = User::factory()->create();
@@ -68,9 +29,9 @@ function commandPaletteUser(string $role): User
function openCommandPalette(mixed $page): void
{
- waitForCommandPaletteTestId($page, 'app-content-shell');
+ waitFor($page, '@app-content-shell');
$page->keys('@app-content-shell', 'ControlOrMeta+k');
- waitForCommandPaletteTestId($page, 'command-palette-input');
+ waitFor($page, '@command-palette-input');
}
test('the shortcut opens the palette and escape closes it', function () {
@@ -85,7 +46,7 @@ test('the shortcut opens the palette and escape closes it', function () {
->assertAttribute('@command-palette-input', 'placeholder', 'Search channels, pages...');
$page->keys('@command-palette-input', 'Escape');
- waitForCommandPaletteGone($page, 'command-palette');
+ waitForGone($page, '@command-palette');
$page->assertMissing('@command-palette')->assertNoJavaScriptErrors();
});
@@ -140,7 +101,7 @@ test('typing filters the list and exposes settings and insights pages', function
openCommandPalette($page);
$page->type('@command-palette-input', 'set');
- waitForCommandPaletteTestId($page, 'command-palette-item-settings-profile');
+ waitFor($page, '@command-palette-item-settings-profile');
$page->assertVisible('@command-palette-group-settings')
->assertSeeIn('@command-palette-item-settings-profile', 'Settings → Profile')
@@ -150,7 +111,7 @@ test('typing filters the list and exposes settings and insights pages', function
->assertMissing("@command-palette-item-insights-{$channel->id}");
$page->type('@command-palette-input', 'acme');
- waitForCommandPaletteTestId($page, "command-palette-item-insights-{$channel->id}");
+ waitFor($page, "@command-palette-item-insights-{$channel->id}");
$page->assertVisible("@command-palette-item-channel-{$channel->id}")
->assertSeeIn("@command-palette-item-insights-{$channel->id}", 'Acme LinkedIn → Insights')
@@ -165,7 +126,7 @@ test('an unmatched query shows the empty state', function () {
openCommandPalette($page);
$page->type('@command-palette-input', 'zzqq');
- waitForCommandPaletteTestId($page, 'command-palette-empty');
+ waitFor($page, '@command-palette-empty');
$page->assertSeeIn('@command-palette-empty', 'No results for "zzqq". Try different keywords.')
->assertMissing('@command-palette-group-actions')
@@ -184,10 +145,11 @@ test('selecting a channel opens its publish page and it shows up under recent',
openCommandPalette($page);
$page->type('@command-palette-input', 'acme');
- waitForCommandPaletteTestId($page, "command-palette-item-channel-{$channel->id}");
+ waitFor($page, "@command-palette-item-channel-{$channel->id}");
$page->click("@command-palette-item-channel-{$channel->id}");
$channelPath = parse_url(route('app.channels.publish', $channel), PHP_URL_PATH);
- waitForCommandPalettePath($page, $channelPath);
+ waitForPath($page, $channelPath);
+ waitForState($page, '@publish-page', 'true');
expect($page->script('window.location.pathname'))->toBe($channelPath);
$page->assertMissing('@command-palette');
@@ -207,17 +169,17 @@ test('invite and connect open their dialogs for admins', function () {
openCommandPalette($page);
$page->click('@command-palette-item-action-invite-member');
- waitForCommandPaletteTestId($page, 'invite-member-dialog');
+ waitFor($page, '@invite-member-dialog');
$page->assertVisible('@invite-member-dialog')->assertMissing('@command-palette');
$page->keys('@invite-member-dialog', 'Escape');
- waitForCommandPaletteGone($page, 'invite-member-dialog');
+ waitForGone($page, '@invite-member-dialog');
openCommandPalette($page);
$page->type('@command-palette-input', 'connect');
- waitForCommandPaletteTestId($page, 'command-palette-item-action-connect-channel');
+ waitFor($page, '@command-palette-item-action-connect-channel');
$page->click('@command-palette-item-action-connect-channel');
- waitForCommandPaletteTestId($page, 'connect-channel-dialog');
+ waitFor($page, '@connect-channel-dialog');
$page->assertVisible('@connect-channel-dialog')->assertNoJavaScriptErrors();
});
@@ -239,11 +201,11 @@ test('the shortcut does not open the palette over the post composer', function (
$this->actingAs(commandPaletteUser('admin'));
$page = visit(route('app.posts.index'));
- waitForCommandPaletteTestId($page, 'sidebar-new');
+ waitFor($page, '@sidebar-new');
$page->click('@sidebar-new');
- waitForCommandPaletteTestId($page, 'sidebar-new-post');
+ waitFor($page, '@sidebar-new-post');
$page->click('@sidebar-new-post');
- waitForCommandPaletteTestId($page, 'post-composer-dialog');
+ waitFor($page, '@post-composer-dialog');
$page->keys('@post-composer-dialog', 'ControlOrMeta+k');
diff --git a/tests/Browser/ComposerApprovalTest.php b/tests/Browser/ComposerApprovalTest.php
index 15ddcf726..2e0ceeac0 100644
--- a/tests/Browser/ComposerApprovalTest.php
+++ b/tests/Browser/ComposerApprovalTest.php
@@ -13,33 +13,6 @@ use App\Models\User;
use App\Models\Workspace;
use App\Support\PostingSchedule;
-function waitForComposerApprovalTestId(mixed $page, string $testId): void
-{
- $page->script(<<<JS
- (async () => {
- for (let attempt = 0; attempt < 100; attempt++) {
- const sheet = document.querySelector('[data-testid="post-composer-dialog"]');
- if (sheet?.getAttribute('data-state') === 'open'
- && sheet.getAnimations().every((animation) => animation.playState !== 'running')
- && document.querySelector('[data-testid="{$testId}"]')?.getBoundingClientRect().height > 0) return;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })();
- JS);
-}
-
-function waitForComposerApprovalClosed(mixed $page): void
-{
- $page->script(<<<'JS'
- (async () => {
- for (let attempt = 0; attempt < 100; attempt++) {
- if (!document.querySelector('[data-testid="post-composer-dialog"]')) return;
- await new Promise((resolve) => setTimeout(resolve, 100));
- }
- })();
- JS);
-}
-
/**
* @return array{0: Workspace, 1: SocialAccount, 2: User}
*/
@@ -79,11 +52,13 @@ test('a requester never sees publish now and requests approval for the queue', f
$this->actingAs($requester);
$page = visit(route('app.posts.create'));
- waitForComposerApprovalTestId($page, 'composer-add-account');
+ waitForOpen($page, '@post-composer-dialog');
+ waitFor($page, '@composer-add-account');
$page->click('@composer-add-account')
->click("@composer-account-option-{$channel->id}")
->fill("@composer-caption-{$channel->id}", 'Please approve me');
- waitForComposerApprovalTestId($page, 'composer-submit');
+ waitForOpen($page, '@post-composer-dialog');
+ waitFor($page, '@composer-submit');
expect(composerApprovalSubmitText($page))->toBe('Save and request approval');
@@ -96,7 +71,7 @@ test('a requester never sees publish now and requests approval for the queue', f
->assertMissing('@composer-schedule-now')
->click('@composer-schedule-top')
->click('@composer-submit');
- waitForComposerApprovalClosed($page);
+ waitForGone($page, '@post-composer-dialog');
$post = Post::query()->where('workspace_id', $workspace->id)->sole();
@@ -122,7 +97,8 @@ test('editing a pending queue request starts on its stored position', function (
$this->actingAs($requester);
$page = visit(route('app.posts.edit', $post));
- waitForComposerApprovalTestId($page, 'composer-submit');
+ waitForOpen($page, '@post-composer-dialog');
+ waitFor($page, '@composer-submit');
expect($page->script('document.querySelector("[data-testid=composer-submit]").dataset.scheduleMode'))->toBe('top')
->and(composerApprovalSubmitText($page))->toBe('Save and request approval');
@@ -138,11 +114,13 @@ test('owners and admins keep publish now and their default action', function (st
$this->actingAs($user->fresh());
$page = visit(route('app.posts.create'));
- waitForComposerApprovalTestId($page, 'composer-add-account');
+ waitForOpen($page, '@post-composer-dialog');
+ waitFor($page, '@composer-add-account');
$page->click('@composer-add-account')
->click("@composer-account-option-{$channel->id}")
->fill("@composer-caption-{$channel->id}", 'Straight out');
- waitForComposerApprovalTestId($page, 'composer-submit');
+ waitForOpen($page, '@post-composer-dialog');
+ waitFor($page, '@composer-submit');
expect($page->script('document.querySelector("[data-testid=composer-submit]").dataset.scheduleMode'))->toBe('now')
->and(composerApprovalSubmitText($page))->not->toBe('Save and request approval');
@@ -173,7 +151,8 @@ test('editing a pending custom time request starts on custom with its date', fun
expect($post->status)->toBe(PostStatus::PendingApproval);
$page = visit(route('app.posts.edit', $post));
- waitForComposerApprovalTestId($page, 'composer-submit');
+ waitForOpen($page, '@post-composer-dialog');
+ waitFor($page, '@composer-submit');
$day = $at->year === now()->year ? $at->format('M j') : $at->format('M j, Y');
diff --git a/tests/Browser/ComposerAutosaveTest.php b/tests/Browser/ComposerAutosaveTest.php
index fab683974..486d1971e 100644
--- a/tests/Browser/ComposerAutosaveTest.php
+++ b/tests/Browser/ComposerAutosaveTest.php
@@ -10,36 +10,6 @@ use App\Models\User;
use App\Models\Workspace;
use Carbon\CarbonImmutable;
-/**
- * Wait for a data-testid element to mount and lay out. Pest browser `@`
- * selectors resolve to data-testid, and assertions do not auto-wait on SPA paint.
- */
-function waitForComposerAutosaveTestId(mixed $page, string $testId): void
-{
- $page->script(<<<JS
- (async () => {
- const sel = '[data-testid="{$testId}"]';
- for (let i = 0; i < 100; i++) {
- const el = document.querySelector(sel);
- if (el && el.getBoundingClientRect().height > 0) return;
- await new Promise((r) => setTimeout(r, 50));
- }
- })();
- JS);
-}
-
-function waitForComposerAutosaveCondition(mixed $page, string $condition): void
-{
- $page->script(<<<JS
- (async () => {
- for (let i = 0; i < 100; i++) {
- if ({$condition}) return;
- await new Promise((r) => setTimeout(r, 50));
- }
- })();
- JS);
-}
-
/**
* @return array{0: User, 1: Workspace, 2: SocialAccount}
*/
@@ -68,15 +38,15 @@ function composerAutosaveJs(User $user, Workspace $workspace): string
function openComposerForAutosave(mixed $page): void
{
- waitForComposerAutosaveTestId($page, 'posts-new-post');
+ waitFor($page, '@posts-new-post');
$page->click('@posts-new-post');
- waitForComposerAutosaveTestId($page, 'composer-base-content');
+ waitFor($page, '@composer-base-content');
}
function closeComposerForAutosave(mixed $page): void
{
$page->click('@composer-close');
- waitForComposerAutosaveCondition($page, '!document.querySelector(\'[data-testid="post-composer-dialog"]\')');
+ waitForGone($page, '@post-composer-dialog');
}
/**
@@ -118,13 +88,13 @@ test('an unfinished post is offered back and resume restores its text and channe
expect($page->script("{$draft}.content"))->toBe('Half written idea');
openComposerForAutosave($page);
- waitForComposerAutosaveTestId($page, 'composer-resume-dialog');
+ waitFor($page, '@composer-resume-dialog');
$page->assertSeeIn('@composer-resume-preview', 'Half written idea')
->assertVisible('@composer-resume-accounts')
->assertSeeIn('@composer-resume-discard', 'Discard')
->assertSeeIn('@composer-resume-confirm', 'Resume post')
->click('@composer-resume-confirm');
- waitForComposerAutosaveCondition($page, '!document.querySelector(\'[data-testid="composer-resume-dialog"]\')');
+ waitForGone($page, '@composer-resume-dialog');
$page->assertValue("@composer-caption-{$account->id}", 'Half written idea')
->assertVisible("@composer-account-{$account->id}")
@@ -141,9 +111,9 @@ test('discarding the unfinished post clears it so the next open does not ask aga
closeComposerForAutosave($page);
openComposerForAutosave($page);
- waitForComposerAutosaveTestId($page, 'composer-resume-dialog');
+ waitFor($page, '@composer-resume-dialog');
$page->click('@composer-resume-discard');
- waitForComposerAutosaveCondition($page, '!document.querySelector(\'[data-testid="composer-resume-dialog"]\')');
+ waitForGone($page, '@composer-resume-dialog');
$page->assertValue('@composer-base-content', '');
$draft = composerAutosaveJs($user, $workspace);
@@ -163,7 +133,7 @@ test('saving a draft clears the unfinished post', function () {
openComposerForAutosave($page);
writeUnfinishedPost($page, $account, 'Saved for real');
$page->click('@composer-save-draft');
- waitForComposerAutosaveCondition($page, '!document.querySelector(\'[data-testid="post-composer-dialog"]\')');
+ waitForGone($page, '@post-composer-dialog');
expect(Post::where('workspace_id', $workspace->id)->count())->toBe(1);
$draft = composerAutosaveJs($user, $workspace);
@@ -190,7 +160,7 @@ test('editing an existing post never offers the unfinished post', function () {
closeComposerForAutosave($page);
$edit = $page->navigate(route('app.posts.edit', $post));
- waitForComposerAutosaveTestId($edit, 'composer-base-content');
+ waitFor($edit, '@composer-base-content');
$edit->assertValue('@composer-base-content', 'Existing post')
->assertMissing('@composer-resume-dialog');
@@ -216,10 +186,10 @@ test('resume drops expired temporary uploads and keeps media owned by an idea or
]);
openComposerForAutosave($page);
- waitForComposerAutosaveTestId($page, 'composer-resume-dialog');
+ waitFor($page, '@composer-resume-dialog');
$page->click('@composer-resume-confirm');
- waitForComposerAutosaveTestId($page, "composer-{$account->id}-media-item-1");
- waitForComposerAutosaveCondition($page, "{$draft}?.media?.length === 2");
+ waitFor($page, "@composer-{$account->id}-media-item-1");
+ waitForCondition($page, "{$draft}?.media?.length === 2");
expect($page->script("document.querySelectorAll('[data-testid^=\"composer-{$account->id}-media-item-\"]').length"))->toBe(2)
->and($page->script("{$draft}?.media?.map((item) => item.id) ?? null"))->toBe(['fresh-upload', 'owned-media']);
@@ -250,7 +220,7 @@ test('the composer still works when browser storage throws', function () {
$page->assertMissing('@composer-resume-dialog');
writeUnfinishedPost($page, $account, 'Still saves');
$page->click('@composer-save-draft');
- waitForComposerAutosaveCondition($page, '!document.querySelector(\'[data-testid="post-composer-dialog"]\')');
+ waitForGone($page, '@post-composer-dialog');
expect(Post::where('workspace_id', $workspace->id)->sole()->content)->toBe('Still saves');
$page->assertNoJavaScriptErrors();
@@ -273,9 +243,9 @@ test('an idea opened as a post neither prompts nor overwrites the unfinished pos
seedComposerAutosave($page, $user, $workspace->id, ['content' => 'Original unfinished', 'accountIds' => [$account->id]]);
$page->navigate(route('app.create.ideas.show', $idea));
- waitForComposerAutosaveTestId($page, 'idea-editor-create-post');
+ waitFor($page, '@idea-editor-create-post');
$page->click('@idea-editor-create-post');
- waitForComposerAutosaveCondition($page, 'document.querySelector(\'[data-testid="composer-base-content"]\')?.value === "Hello from the idea"');
+ waitForState($page, '@composer-base-content', "element.value === 'Hello from the idea'");
$page->assertMissing('@composer-resume-dialog')
->fill('@composer-base-content', 'Edited idea text');
closeComposerForAutosave($page);
@@ -284,7 +254,7 @@ test('an idea opened as a post neither prompts nor overwrites the unfinished pos
$page->navigate(route('app.posts.index'));
openComposerForAutosave($page);
- waitForComposerAutosaveTestId($page, 'composer-resume-dialog');
+ waitFor($page, '@composer-resume-dialog');
$page->assertSeeIn('@composer-resume-preview', 'Original unfinished')
->assertNoJavaScriptErrors();
});
@@ -303,9 +273,9 @@ test('a custom date already in the past falls back to the default mode', functio
]);
openComposerForAutosave($page);
- waitForComposerAutosaveTestId($page, 'composer-resume-dialog');
+ waitFor($page, '@composer-resume-dialog');
$page->click('@composer-resume-confirm');
- waitForComposerAutosaveTestId($page, 'composer-submit');
+ waitFor($page, '@composer-submit');
expect($page->script('document.querySelector("[data-testid=composer-submit]").dataset.scheduleMode'))->toBe('now');
$page->assertNoJavaScriptErrors();
@@ -326,11 +296,11 @@ test('a failed save keeps the unfinished post and marks a pruned upload on its t
]);
openComposerForAutosave($page);
- waitForComposerAutosaveTestId($page, 'composer-resume-dialog');
+ waitFor($page, '@composer-resume-dialog');
$page->click('@composer-resume-confirm');
- waitForComposerAutosaveTestId($page, "composer-{$account->id}-media-item-0");
+ waitFor($page, "@composer-{$account->id}-media-item-0");
$page->click('@composer-save-draft');
- waitForComposerAutosaveTestId($page, "composer-{$account->id}-media-error-0");
+ waitFor($page, "@composer-{$account->id}-media-error-0");
$page->assertSeeIn("@composer-{$account->id}-media-error-0", 'This upload expired. Add the file again.')
->assertVisible('@post-composer-dialog');
@@ -352,14 +322,14 @@ test('resuming a single channel adopts its own caption as the post text', functi
]);
openComposerForAutosave($page);
- waitForComposerAutosaveTestId($page, 'composer-resume-dialog');
+ waitFor($page, '@composer-resume-dialog');
$page->click('@composer-resume-confirm');
- waitForComposerAutosaveTestId($page, "composer-caption-{$account->id}");
- waitForComposerAutosaveCondition($page, "{$draft}?.content === 'Channel text'");
+ waitFor($page, "@composer-caption-{$account->id}");
+ waitForCondition($page, "{$draft}?.content === 'Channel text'");
$page->assertValue("@composer-caption-{$account->id}", 'Channel text')
->fill("@composer-caption-{$account->id}", 'Channel text edited');
- waitForComposerAutosaveCondition($page, "{$draft}?.content === 'Channel text edited'");
+ waitForCondition($page, "{$draft}?.content === 'Channel text edited'");
expect($page->script("{$draft}.overrides['{$account->id}']?.content ?? null"))->toBeNull();
$page->assertNoJavaScriptErrors();
@@ -376,11 +346,11 @@ test('logging out removes the user\'s unfinished posts in every workspace, keepi
setBrowserStorageItem($page, $user, 'emoji.recents', ['🚀']);
$page->script("localStorage.setItem('trypost:unrelated', 'kept')");
- waitForComposerAutosaveTestId($page, 'sidebar-workspace-menu');
+ waitFor($page, '@sidebar-workspace-menu');
$page->click('@sidebar-workspace-menu');
- waitForComposerAutosaveTestId($page, 'logout-button');
+ waitFor($page, '@logout-button');
$page->click('@logout-button');
- waitForComposerAutosaveCondition($page, "{$draft} === null");
+ waitForCondition($page, "{$draft} === null");
expect(browserStorageItem($page, $user, 'composer.autosave', 'other-workspace'))->toBeNull()
->and(browserStorageItem($page, $user, 'emoji.recents'))->toBe(['🚀'])
@@ -404,9 +374,9 @@ test('a restored custom time keeps its moment in the channel zone', function ()
]);
openComposerForAutosave($page);
- waitForComposerAutosaveTestId($page, 'composer-resume-dialog');
+ waitFor($page, '@composer-resume-dialog');
$page->click('@composer-resume-confirm');
- waitForComposerAutosaveTestId($page, 'composer-submit');
+ waitFor($page, '@composer-submit');
$local = CarbonImmutable::parse("{$day} 10:00", 'America/Sao_Paulo');
expect(trim((string) $page->script('document.querySelector("[data-testid=composer-schedule-trigger]").textContent')))
@@ -414,7 +384,7 @@ test('a restored custom time keeps its moment in the channel zone', function ()
->and($page->script('document.querySelector("[data-testid=composer-submit]").dataset.scheduleMode'))->toBe('custom');
$page->click('@composer-submit');
- waitForComposerAutosaveCondition($page, '!document.querySelector(\'[data-testid="post-composer-dialog"]\')');
+ waitForGone($page, '@post-composer-dialog');
expect(Post::query()->where('workspace_id', $workspace->id)->sole()->scheduled_at->toIso8601String())
->toBe($local->utc()->toIso8601String());
@@ -435,11 +405,11 @@ test('an unfinished post from the old shared editor restores one card per networ
]);
openComposerForAutosave($page);
- waitForComposerAutosaveTestId($page, 'composer-resume-dialog');
+ waitFor($page, '@composer-resume-dialog');
$page->click('@composer-resume-confirm');
- waitForComposerAutosaveTestId($page, "composer-caption-{$linkedin->id}");
+ waitFor($page, "@composer-caption-{$linkedin->id}");
- waitForComposerAutosaveCondition($page, "{$draft}?.overrides?.['{$linkedin->id}']?.content !== undefined");
+ waitForCondition($page, "{$draft}?.overrides?.['{$linkedin->id}']?.content !== undefined");
expect($page->script("{$draft}.overrides"))->toEqual([
$linkedin->id => ['content' => 'Shared text', 'media' => []],
$x->id => ['content' => 'X text', 'media' => []],
@@ -474,14 +444,14 @@ test('two pages of one network restore the text of the page that owns one', func
]);
openComposerForAutosave($page);
- waitForComposerAutosaveTestId($page, 'composer-resume-dialog');
+ waitFor($page, '@composer-resume-dialog');
$page->click('@composer-resume-confirm');
- waitForComposerAutosaveTestId($page, "composer-caption-{$first->id}");
+ waitFor($page, "@composer-caption-{$first->id}");
$page->assertValue("@composer-caption-{$first->id}", 'Second page text')
->assertNoJavaScriptErrors()
->click('@composer-save-draft');
- waitForComposerAutosaveCondition($page, '!document.querySelector(\'[data-testid="post-composer-dialog"]\')');
+ waitForGone($page, '@post-composer-dialog');
expect(composerAutosaveSavedContents($workspace))->toEqual([
$first->id => 'Second page text',
@@ -498,16 +468,16 @@ test('resuming an unfinished post keeps its thread replies', function () {
openComposerForAutosave($page);
writeUnfinishedPost($page, $bluesky, 'Thread root');
$page->click('@thread-start');
- waitForComposerAutosaveTestId($page, 'thread-reply-0');
+ waitFor($page, '@thread-reply-0');
$page->fill('@thread-reply-0', 'Kept reply');
$draft = composerAutosaveJs($user, $workspace);
- waitForComposerAutosaveCondition($page, "{$draft}?.overrides?.['{$bluesky->id}']?.meta?.thread_replies?.[0] === 'Kept reply'");
+ waitForCondition($page, "{$draft}?.overrides?.['{$bluesky->id}']?.meta?.thread_replies?.[0] === 'Kept reply'");
closeComposerForAutosave($page);
openComposerForAutosave($page);
- waitForComposerAutosaveTestId($page, 'composer-resume-dialog');
+ waitFor($page, '@composer-resume-dialog');
$page->click('@composer-resume-confirm');
- waitForComposerAutosaveTestId($page, 'thread-reply-collapsed-0');
+ waitFor($page, '@thread-reply-collapsed-0');
$page->assertSeeIn('@thread-reply-collapsed-0', 'Kept reply')
->assertValue("@composer-caption-{$bluesky->id}", 'Thread root')
diff --git a/tests/Browser/ComposerCanvaMenuTest.php b/tests/Browser/ComposerCanvaMenuTest.php
index b8271c98b..951d133dd 100644
--- a/tests/Browser/ComposerCanvaMenuTest.php
+++ b/tests/Browser/ComposerCanvaMenuTest.php
@@ -16,27 +16,6 @@ use Illuminate\Support\Facades\Queue;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
-function waitForComposerCanvaCondition(mixed $page, string $condition, int $attempts = 100): void
-{
- $page->script(<<<JS
- (async () => {
- for (let attempt = 0; attempt < {$attempts}; attempt++) {
- if ({$condition}) return;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })();
- JS);
-}
-
-function waitForComposerCanvaTestId(mixed $page, string $testId, int $rounds = 1): void
-{
- $visible = "document.querySelector('[data-testid=\"{$testId}\"]')?.getBoundingClientRect().height > 0";
-
- for ($round = 0; $round < $rounds && ! $page->script("Boolean({$visible})"); $round++) {
- waitForComposerCanvaCondition($page, $visible);
- }
-}
-
/**
* @return array{page: mixed, user: User, workspace: Workspace}
*/
@@ -61,7 +40,7 @@ function openComposerWithOnlyCanva(mixed $test): array
$test->actingAs($user);
$page = visit(route('app.posts.create'));
- waitForComposerCanvaCondition($page, "document.querySelector('[data-testid=\"composer-base-toolbar\"]')?.getBoundingClientRect().height > 0", attempts: 300);
+ waitFor($page, '@composer-base-toolbar');
return ['page' => $page, 'user' => $user, 'workspace' => $workspace];
}
@@ -70,9 +49,9 @@ test('the Canva submenu lists the five presets with their sizes, Square first an
['page' => $page] = openComposerWithOnlyCanva($this);
$page->click('@composer-base-media-source-menu');
- waitForComposerCanvaTestId($page, 'media-source-canva');
+ waitFor($page, '@media-source-canva');
$page->click('@media-source-canva');
- waitForComposerCanvaTestId($page, 'canva-preset-square');
+ waitFor($page, '@canva-preset-square');
expect($page->script("[...document.querySelectorAll('[data-testid^=\"canva-preset-\"]:not([data-testid\$=\"-default\"])')].map((element) => element.dataset.testid)"))
->toBe(['canva-preset-square', 'canva-preset-portrait_4_5', 'canva-preset-portrait_3_4', 'canva-preset-landscape', 'canva-preset-story']);
@@ -91,7 +70,7 @@ test('the Canva entry shows the official Canva logo', function () {
['page' => $page] = openComposerWithOnlyCanva($this);
$page->click('@composer-base-media-source-menu');
- waitForComposerCanvaTestId($page, 'media-source-canva');
+ waitFor($page, '@media-source-canva');
$page->assertPresent('[data-testid="media-source-canva"] svg path[fill="#7D2AE7"]')
->assertNoJavaScriptErrors();
@@ -108,9 +87,9 @@ function pickCanvaPresetWithStubbedPopup(mixed $page, string $preset, bool $seve
$page->script("window.__canvaOpened = []; window.open = (url) => { window.__canvaOpened.push(url); return {$popup}; }; true;");
$page->click('@composer-base-media-source-menu');
- waitForComposerCanvaTestId($page, 'media-source-canva');
+ waitFor($page, '@media-source-canva');
$page->click('@media-source-canva');
- waitForComposerCanvaTestId($page, "canva-preset-{$preset}");
+ waitFor($page, "@canva-preset-{$preset}");
$page->click("@canva-preset-{$preset}");
$opened = $page->script('window.__canvaOpened');
@@ -153,7 +132,7 @@ test('a preset opens the Canva popup and a message carrying its nonce becomes a
true;
JS);
- waitForComposerCanvaTestId($page, 'composer-media-item');
+ waitFor($page, '@composer-media-item');
$page->assertCount('@composer-media-item', 1)
->assertNoJavaScriptErrors();
});
@@ -193,10 +172,10 @@ test('with the opener severed, the real return page reaches the composer through
], $pem, 'RS256', 'browser-kid');
$popup = visit(route('app.integrations.canva.return', ['correlation_jwt' => $jwt]));
- waitForComposerCanvaTestId($popup, 'media-source-popup', rounds: 6);
+ waitFor($popup, '@media-source-popup');
$popup->assertAttribute('@media-source-popup', 'data-success', 'true');
- waitForComposerCanvaTestId($page, 'composer-import-item', rounds: 6);
+ waitFor($page, '@composer-import-item');
$page->assertCount('@composer-import-item', 1)
->assertNoJavaScriptErrors();
Queue::assertPushed(ExportCanvaDesign::class, fn (ExportCanvaDesign $job): bool => $job->designId === 'DAF-browser');
@@ -216,7 +195,7 @@ test('with every transport lost, the composer finds the return on the server', f
'replaces' => null,
], 3600);
- waitForComposerCanvaTestId($page, 'composer-media-item', rounds: 12);
+ waitFor($page, '@composer-media-item', seconds: 60);
$page->assertCount('@composer-media-item', 1)
->assertNoJavaScriptErrors();
});
diff --git a/tests/Browser/ComposerEditInCanvaTest.php b/tests/Browser/ComposerEditInCanvaTest.php
index 0e25c81a0..44ef8b8c8 100644
--- a/tests/Browser/ComposerEditInCanvaTest.php
+++ b/tests/Browser/ComposerEditInCanvaTest.php
@@ -13,23 +13,6 @@ use App\Support\MediaImportStatus;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
-function waitForEditInCanvaCondition(mixed $page, string $condition, int $attempts = 100): void
-{
- $page->script(<<<JS
- (async () => {
- for (let attempt = 0; attempt < {$attempts}; attempt++) {
- if ({$condition}) return;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })();
- JS);
-}
-
-function waitForEditInCanvaTestId(mixed $page, string $testId): void
-{
- waitForEditInCanvaCondition($page, "document.querySelector('[data-testid=\"{$testId}\"]')?.getBoundingClientRect().height > 0");
-}
-
/**
* A finished Canva import: a temporary upload that remembers its design.
*
@@ -87,9 +70,9 @@ function editInCanvaPickSquare(mixed $page, string $toolbarPrefix): string
{
['query' => $query] = editInCanvaStubbedPopup($page, function () use ($page, $toolbarPrefix): void {
$page->click("@{$toolbarPrefix}-media-source-menu");
- waitForEditInCanvaTestId($page, 'media-source-canva');
+ waitFor($page, '@media-source-canva');
$page->click('@media-source-canva');
- waitForEditInCanvaTestId($page, 'canva-preset-square');
+ waitFor($page, '@canva-preset-square');
$page->click('@canva-preset-square');
});
@@ -128,10 +111,10 @@ test('the Canva button shows only on Canva-made tiles and replaces the tile in p
$channelEdited = editInCanvaBrowserImport($user, $workspace, 'DAF-channel-edited', $channelMade['media']->id);
$page = visit(route('app.posts.create'));
- waitForEditInCanvaCondition($page, "document.querySelector('[data-testid=\"composer-add-account\"]')?.getBoundingClientRect().height > 0", attempts: 300);
+ waitFor($page, '@composer-add-account');
editInCanvaDeliver($page, editInCanvaPickSquare($page, 'composer-base'), $shared['import'], null);
- waitForEditInCanvaTestId($page, 'composer-media-item-0');
+ waitFor($page, '@composer-media-item-0');
$png = base64_encode((string) file_get_contents(base_path('tests/fixtures/crop-quadrants.png')));
$page->script(<<<JS
@@ -144,7 +127,7 @@ test('the Canva button shows only on Canva-made tiles and replaces the tile in p
input.dispatchEvent(new Event('change', { bubbles: true }));
})();
JS);
- waitForEditInCanvaTestId($page, 'composer-media-item-1');
+ waitFor($page, '@composer-media-item-1');
$uploadedSrc = editInCanvaTileSrc($page, 'composer', 1);
@@ -153,11 +136,11 @@ test('the Canva button shows only on Canva-made tiles and replaces the tile in p
->assertAttribute('@composer-edit-canva-0', 'aria-label', 'Edit DAF-shared.png in Canva')
->hover('@composer-dropzone');
$page->script('document.activeElement?.blur(); true;');
- waitForEditInCanvaCondition($page, "getComputedStyle(document.querySelector('[data-testid=\"composer-edit-canva-0\"]').parentElement).opacity === '0'");
+ waitForState($page, '@composer-edit-canva-0', "getComputedStyle(element.parentElement).opacity === '0'");
expect($page->script("getComputedStyle(document.querySelector('[data-testid=\"composer-edit-canva-0\"]').parentElement).opacity"))->toBe('0');
$page->hover('@composer-media-item-0');
- waitForEditInCanvaCondition($page, "getComputedStyle(document.querySelector('[data-testid=\"composer-edit-canva-0\"]').parentElement).opacity === '1'");
+ waitForState($page, '@composer-edit-canva-0', "getComputedStyle(element.parentElement).opacity === '1'");
expect($page->script("getComputedStyle(document.querySelector('[data-testid=\"composer-edit-canva-0\"]').parentElement).opacity"))->toBe('1');
['path' => $path, 'query' => $query] = editInCanvaStubbedPopup($page, fn () => $page->click('@composer-edit-canva-0'));
@@ -169,7 +152,7 @@ test('the Canva button shows only on Canva-made tiles and replaces the tile in p
$exporting = (string) Str::uuid();
MediaImportStatus::pending($exporting, $user->id, $workspace->id, $shared['media']->id);
editInCanvaDeliver($page, (string) data_get($query, 'nonce'), $exporting, $shared['media']->id);
- waitForEditInCanvaTestId($page, 'composer-replacing-0');
+ waitFor($page, '@composer-replacing-0');
$page->assertPresent('@composer-replacing-0')
->assertMissing('@composer-import-item')
@@ -178,7 +161,7 @@ test('the Canva button shows only on Canva-made tiles and replaces the tile in p
->and($page->script("document.querySelectorAll('[data-testid^=\"composer-media-item-\"]').length"))->toBe(2);
MediaImportStatus::complete($exporting, $sharedEdited['media']);
- waitForEditInCanvaCondition($page, "document.querySelector('[data-testid=\"composer-media-item-0\"] img')?.getAttribute('src') === '{$sharedEdited['media']->url}'");
+ waitForState($page, '@composer-media-item-0 img', "element.getAttribute('src') === '{$sharedEdited['media']->url}'");
expect(editInCanvaTileSrc($page, 'composer', 0))->toBe($sharedEdited['media']->url)
->and(editInCanvaTileSrc($page, 'composer', 1))->toBe($uploadedSrc)
@@ -186,10 +169,10 @@ test('the Canva button shows only on Canva-made tiles and replaces the tile in p
$page->click('@composer-add-account')
->click("@composer-account-option-{$channel->id}");
- waitForEditInCanvaTestId($page, "composer-{$channel->id}-media-item-1");
+ waitFor($page, "@composer-{$channel->id}-media-item-1");
editInCanvaDeliver($page, editInCanvaPickSquare($page, "composer-{$channel->id}"), $channelMade['import'], null);
- waitForEditInCanvaTestId($page, "composer-{$channel->id}-media-item-2");
+ waitFor($page, "@composer-{$channel->id}-media-item-2");
$page->assertPresent("@composer-{$channel->id}-edit-canva-0")
->assertMissing("@composer-{$channel->id}-edit-canva-1")
@@ -200,16 +183,16 @@ test('the Canva button shows only on Canva-made tiles and replaces the tile in p
expect(data_get($channelQuery, 'media'))->toBe($channelMade['media']->id);
editInCanvaDeliver($page, (string) data_get($channelQuery, 'nonce'), $channelEdited['import'], $channelMade['media']->id);
- waitForEditInCanvaCondition($page, "document.querySelector('[data-testid=\"composer-{$channel->id}-media-item-2\"] img')?.getAttribute('src') === '{$channelEdited['media']->url}'");
+ waitForState($page, "@composer-{$channel->id}-media-item-2 img", "element.getAttribute('src') === '{$channelEdited['media']->url}'");
expect(editInCanvaTileSrc($page, "composer-{$channel->id}", 2))->toBe($channelEdited['media']->url)
->and(editInCanvaTileSrc($page, "composer-{$channel->id}", 0))->toBe($sharedEdited['media']->url)
->and(editInCanvaTileSrc($page, "composer-{$channel->id}", 1))->toBe($uploadedSrc)
->and($page->script("document.querySelectorAll('[data-testid^=\"composer-{$channel->id}-media-item-\"]').length"))->toBe(3);
- waitForEditInCanvaCondition($page, "document.querySelector('[data-testid=\"composer-save-draft\"]')?.disabled === false");
+ waitForState($page, '@composer-save-draft', 'element.disabled === false');
$page->click('@composer-save-draft');
- waitForEditInCanvaCondition($page, "!document.querySelector('[data-testid=\"post-composer-dialog\"]')", attempts: 200);
+ waitForGone($page, '@post-composer-dialog');
$saved = Post::query()->where('workspace_id', $workspace->id)->sole()->media;
@@ -248,7 +231,7 @@ test('the idea editor replaces a Canva tile in place and the save releases the r
$edited = editInCanvaBrowserImport($user, $workspace, 'DAF-idea-edited', $original->id);
$page = visit(route('app.create.ideas.show', $idea));
- waitForEditInCanvaTestId($page, 'idea-media-item-1');
+ waitFor($page, '@idea-media-item-1');
$page->assertPresent('@idea-edit-canva-0')
->assertMissing('@idea-edit-canva-1');
@@ -259,13 +242,13 @@ test('the idea editor replaces a Canva tile in place and the save releases the r
->and(data_get($query, 'media'))->toBe($original->id);
editInCanvaDeliver($page, (string) data_get($query, 'nonce'), $edited['import'], $original->id);
- waitForEditInCanvaCondition($page, "document.querySelector('[data-testid=\"idea-media-item-0\"] img')?.getAttribute('src') === '{$edited['media']->url}'");
+ waitForState($page, '@idea-media-item-0 img', "element.getAttribute('src') === '{$edited['media']->url}'");
expect(editInCanvaTileSrc($page, 'idea', 0))->toBe($edited['media']->url)
->and(editInCanvaTileSrc($page, 'idea', 1))->toBe($plain->url);
$page->click('@idea-editor-save');
- waitForEditInCanvaCondition($page, "!document.querySelector('[data-testid=\"idea-editor\"]')", attempts: 200);
+ waitForGone($page, '@idea-editor');
expect(collect($idea->refresh()->media)->pluck('id')->all())->toBe([$edited['media']->id, $plain->id])
->and(Media::query()->find($original->id))->toBeNull()
diff --git a/tests/Browser/ComposerGooglePhotosTest.php b/tests/Browser/ComposerGooglePhotosTest.php
index 84ef09bc5..50f5927ba 100644
--- a/tests/Browser/ComposerGooglePhotosTest.php
+++ b/tests/Browser/ComposerGooglePhotosTest.php
@@ -25,31 +25,6 @@ const COMPOSER_GOOGLE_PHOTOS_PICKER_URI = 'https://127.0.0.1:9/picker/'.COMPOSER
const COMPOSER_GOOGLE_PHOTOS_NONCE_PATTERN = '/^[A-Za-z0-9_-]{16,64}$/';
-/**
- * Poll from the page until `$condition` holds (never sleep(): the test server
- * only ticks while Pest awaits Playwright).
- */
-function waitForComposerGooglePhotosCondition(mixed $page, string $condition): void
-{
- $page->script(<<<JS
- (async () => {
- for (let attempt = 0; attempt < 200; attempt++) {
- if ({$condition}) return;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })();
- JS);
-}
-
-function waitForComposerGooglePhotosTestId(mixed $page, string $testId, int $rounds = 1): void
-{
- $visible = "document.querySelector('[data-testid=\"{$testId}\"]')?.getBoundingClientRect().height > 0";
-
- for ($round = 0; $round < $rounds && ! $page->script("Boolean({$visible})"); $round++) {
- waitForComposerGooglePhotosCondition($page, $visible);
- }
-}
-
function openComposerForGooglePhotos(mixed $test): mixed
{
$user = User::factory()->create();
@@ -61,7 +36,7 @@ function openComposerForGooglePhotos(mixed $test): mixed
$test->actingAs($user);
$page = visit(route('app.posts.create'));
- waitForComposerGooglePhotosTestId($page, 'composer-base-media-source-menu', rounds: 4);
+ waitFor($page, '@composer-base-media-source-menu', seconds: 40);
return $page;
}
@@ -69,7 +44,7 @@ function openComposerForGooglePhotos(mixed $test): mixed
function chooseComposerGooglePhotos(mixed $page): void
{
$page->click('@composer-base-media-source-menu');
- waitForComposerGooglePhotosTestId($page, 'media-source-google_photos');
+ waitFor($page, '@media-source-google_photos');
$page->click('@media-source-google_photos');
}
@@ -202,7 +177,7 @@ test('the real sign-in popup opens the picker and every picked photo becomes its
expect((string) rescue(fn (): string => $popup->content(), '', report: false))->not->toContain('server-photos-token');
foreach (range(1, 4) as $round) {
- waitForComposerGooglePhotosCondition($page, "document.querySelectorAll('[data-testid=\"composer-media-item\"]').length === 2");
+ waitForCount($page, '@composer-media-item', 2);
}
$page->assertNoJavaScriptErrors();
@@ -258,9 +233,9 @@ test('closing the google photos window without picking adds nothing and discards
}));
true;
JS);
- waitForComposerGooglePhotosCondition($page, "window.__photos.finished.some((request) => request.includes('/integrations/google/returns/'))");
+ waitForCondition($page, "window.__photos.finished.some((request) => request.includes('/integrations/google/returns/'))");
$page->script('window.__photos.popup.closed = true; true;');
- waitForComposerGooglePhotosCondition($page, "window.__photos.finished.some((request) => request.startsWith('DELETE ') && request.includes('/media/google-photos/sessions/'))");
+ waitForCondition($page, "window.__photos.finished.some((request) => request.startsWith('DELETE ') && request.includes('/media/google-photos/sessions/'))");
$page->assertNotPresent('@composer-media-item')
->assertNoJavaScriptErrors();
@@ -281,7 +256,7 @@ test('a refused google photos sign-in opens no picker and says why', function ()
config()->set('trypost.media_sources.google_oauth.authorize_url', route('app.integrations.google.callback').'?error=access_denied&ignored');
$popup = visit(googlePhotosSignInUrl($page));
- waitForComposerGooglePhotosTestId($popup, 'media-source-popup');
+ waitFor($popup, '@media-source-popup');
$popup->assertAttribute('@media-source-popup', 'data-success', 'false')
->assertSee(__('posts.composer.media_sources.errors.scope_not_granted'));
@@ -295,7 +270,7 @@ test('a refused google photos sign-in opens no picker and says why', function ()
}));
true;
JS);
- waitForComposerGooglePhotosCondition($page, "document.body.innerText.includes('Try again and allow it')");
+ waitForCondition($page, "document.body.innerText.includes('Try again and allow it')");
$page->assertSee(__('posts.composer.media_sources.errors.scope_not_granted'))
->assertNotPresent('@composer-media-item')
@@ -312,7 +287,7 @@ test('a blocked google photos popup says so and asks the server for nothing', fu
$page->script('window.open = () => null; true;');
chooseComposerGooglePhotos($page);
- waitForComposerGooglePhotosCondition($page, "document.body.innerText.includes('Your browser blocked the window')");
+ waitForCondition($page, "document.body.innerText.includes('Your browser blocked the window')");
$page->assertSee(__('posts.composer.media_sources.errors.popup_blocked'))
->assertNotPresent('@composer-media-item')
diff --git a/tests/Browser/ComposerMediaSourcesTest.php b/tests/Browser/ComposerMediaSourcesTest.php
index 7837643f1..c1cf870b2 100644
--- a/tests/Browser/ComposerMediaSourcesTest.php
+++ b/tests/Browser/ComposerMediaSourcesTest.php
@@ -13,35 +13,6 @@ use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Http;
-/**
- * Poll from the page until `$condition` holds (never sleep(): the test server
- * only ticks while Pest awaits Playwright).
- */
-function waitForComposerMediaSourcesCondition(mixed $page, string $condition): void
-{
- $page->script(<<<JS
- (async () => {
- for (let attempt = 0; attempt < 100; attempt++) {
- if ({$condition}) return;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })();
- JS);
-}
-
-/**
- * Wait for a data-testid element to mount and lay out. Pest browser `@`
- * selectors resolve to data-testid, and assertions do not auto-wait on SPA paint.
- */
-function waitForComposerMediaSourcesTestId(mixed $page, string $testId, int $rounds = 1): void
-{
- $visible = "document.querySelector('[data-testid=\"{$testId}\"]')?.getBoundingClientRect().height > 0";
-
- for ($round = 0; $round < $rounds && ! $page->script("Boolean({$visible})"); $round++) {
- waitForComposerMediaSourcesCondition($page, $visible);
- }
-}
-
function openComposerForMediaSources(mixed $test): mixed
{
$user = User::factory()->create();
@@ -53,7 +24,7 @@ function openComposerForMediaSources(mixed $test): mixed
$test->actingAs($user);
$page = visit(route('app.posts.create'));
- waitForComposerMediaSourcesTestId($page, 'composer-base-toolbar');
+ waitFor($page, '@composer-base-toolbar');
return $page;
}
@@ -64,7 +35,7 @@ function chooseComposerMediaSource(mixed $page, string $prefix, string $source):
for ($attempt = 0; $attempt < 3 && ! $page->script("Boolean({$item})"); $attempt++) {
$page->click("@{$prefix}-media-source-menu");
- waitForComposerMediaSourcesCondition($page, $item);
+ waitFor($page, "@media-source-{$source}");
}
$page->click("@media-source-{$source}");
@@ -149,7 +120,7 @@ test('the toolbar has one media button whose menu lists the upload first, then t
]);
$page = openComposerForMediaSources($this);
- waitForComposerMediaSourcesTestId($page, 'composer-base-media-source-menu');
+ waitFor($page, '@composer-base-media-source-menu');
$page->assertNotPresent('@composer-base-add-media')
->assertNotPresent('@composer-base-media-source-main')
@@ -172,7 +143,7 @@ test('the toolbar has one media button whose menu lists the upload first, then t
JS))->toBe(['heights' => 1, 'centers' => 1, 'icons' => 1]);
$page->click('@composer-base-media-source-menu');
- waitForComposerMediaSourcesTestId($page, 'composer-base-media-source-list');
+ waitFor($page, '@composer-base-media-source-list');
expect($page->script("Array.from(document.querySelectorAll('[data-testid=\"composer-base-media-source-list\"] [data-testid^=\"media-source-\"]')).map((item) => item.dataset.testid)"))
->toBe(['media-source-upload', 'media-source-canva', 'media-source-unsplash']);
@@ -186,7 +157,7 @@ test('the toolbar has one media button whose menu lists the upload first, then t
JS))->toBeTrue();
$page->click('@media-source-unsplash');
- waitForComposerMediaSourcesTestId($page, 'unsplash-dialog');
+ waitFor($page, '@unsplash-dialog');
$page->assertNoJavaScriptErrors();
});
@@ -203,11 +174,11 @@ test('upload from computer in the media menu opens the file picker', function (s
$this->actingAs($user);
$page = visit(route($route));
- waitForComposerMediaSourcesTestId($page, "{$prefix}-media-source-menu");
+ waitFor($page, "@{$prefix}-media-source-menu");
$page->script("HTMLInputElement.prototype.click = function () { if (this.type === 'file') { window.__filePicker = (window.__filePicker ?? 0) + 1; } }; true;");
chooseComposerMediaSource($page, $prefix, 'upload');
- waitForComposerMediaSourcesCondition($page, 'window.__filePicker === 1');
+ waitForCondition($page, 'window.__filePicker === 1');
expect($page->script('window.__filePicker ?? 0'))->toBe(1);
$page->assertNoJavaScriptErrors();
@@ -219,20 +190,20 @@ test('picking an unsplash photo from the menu adds a tile and credits the photog
enableOnlyUnsplashForMediaSources();
$page = openComposerForMediaSources($this);
- waitForComposerMediaSourcesTestId($page, 'composer-base-media-source-menu');
+ waitFor($page, '@composer-base-media-source-menu');
$page->click('@composer-base-media-source-menu');
- waitForComposerMediaSourcesTestId($page, 'media-source-unsplash');
+ waitFor($page, '@media-source-unsplash');
$page->click('@media-source-unsplash');
- waitForComposerMediaSourcesTestId($page, 'unsplash-dialog');
- waitForComposerMediaSourcesTestId($page, 'unsplash-photo-0');
+ waitFor($page, '@unsplash-dialog');
+ waitFor($page, '@unsplash-photo-0');
$page->assertSeeIn('@unsplash-dialog', 'Ana Photographer');
expect($page->script("document.querySelector('[data-testid=\"unsplash-dialog\"] a[href*=\"@sunrise\"]')?.getAttribute('href')"))
->toEndWith('@sunrise?utm_source=trypost&utm_medium=referral');
$page->click('@unsplash-photo-0');
- waitForComposerMediaSourcesTestId($page, 'composer-media-item');
- waitForComposerMediaSourcesCondition($page, "!document.querySelector('[data-testid=\"unsplash-dialog\"]')");
+ waitFor($page, '@composer-media-item');
+ waitForGone($page, '@unsplash-dialog');
$page->assertPresent('@composer-media-item')
->assertNotPresent('@unsplash-dialog')
@@ -250,9 +221,9 @@ test('the unsplash dialog keeps loading pages as the grid scrolls and has no foo
enableOnlyUnsplashForMediaSources();
$page = openComposerForMediaSources($this);
- waitForComposerMediaSourcesTestId($page, 'composer-base-media-source-menu');
+ waitFor($page, '@composer-base-media-source-menu');
chooseComposerMediaSource($page, 'composer-base', 'unsplash');
- waitForComposerMediaSourcesTestId($page, 'unsplash-photo-1');
+ waitFor($page, '@unsplash-photo-1');
$page->assertSeeIn('@unsplash-dialog', 'Bruno Photographer')
->assertNotPresent('@unsplash-photo-2')
@@ -266,9 +237,9 @@ test('an unsplash outage shows an error instead of an empty result', function ()
enableOnlyUnsplashForMediaSources(apiStatus: 403);
$page = openComposerForMediaSources($this);
- waitForComposerMediaSourcesTestId($page, 'composer-base-media-source-menu');
+ waitFor($page, '@composer-base-media-source-menu');
chooseComposerMediaSource($page, 'composer-base', 'unsplash');
- waitForComposerMediaSourcesTestId($page, 'unsplash-error');
+ waitFor($page, '@unsplash-error');
$page->assertSeeIn('@unsplash-error', "Unsplash isn't available right now.")
->assertNotPresent('@unsplash-empty')
@@ -445,18 +416,18 @@ test('picking a google drive file in a single channel adds a tile to that channe
$page = openComposerForMediaSources($this);
$account = SocialAccount::query()->sole();
- waitForComposerMediaSourcesTestId($page, 'composer-add-account');
+ waitFor($page, '@composer-add-account');
$page->click('@composer-add-account');
$page->click("@composer-account-option-{$account->id}");
- waitForComposerMediaSourcesTestId($page, "composer-{$account->id}-media-source-menu");
+ waitFor($page, "@composer-{$account->id}-media-source-menu");
$page->fill("@composer-caption-{$account->id}", 'Drive pick for one channel');
stubGoogleDriveForMediaSources($page);
$page->click("@composer-{$account->id}-media-source-menu");
- waitForComposerMediaSourcesTestId($page, 'media-source-google_drive');
+ waitFor($page, '@media-source-google_drive');
$page->click('@media-source-google_drive');
finishGoogleDriveSignIn($page);
- waitForComposerMediaSourcesTestId($page, "composer-{$account->id}-media-item");
+ waitFor($page, "@composer-{$account->id}-media-item");
$page->assertPresent("@composer-{$account->id}-media-item")
->assertNoJavaScriptErrors();
@@ -469,13 +440,13 @@ test('the drive picker can be clicked, focused and typed in over the composer di
$api = enableOnlyGoogleDriveForMediaSources();
$page = openComposerForMediaSources($this);
- waitForComposerMediaSourcesTestId($page, 'composer-base-media-source-menu');
+ waitFor($page, '@composer-base-media-source-menu');
stubGoogleDriveForMediaSources($page, holdOpen: true);
chooseComposerMediaSource($page, 'composer-base', 'google_drive');
- waitForComposerMediaSourcesCondition($page, "!document.querySelector('[data-testid=\"composer-base-media-source-list\"]')");
+ waitForGone($page, '@composer-base-media-source-list');
finishGoogleDriveSignIn($page);
- waitForComposerMediaSourcesTestId($page, 'drive-picker-search');
- waitForComposerMediaSourcesCondition($page, "document.activeElement?.dataset?.testid === 'drive-picker-search'");
+ waitFor($page, '@drive-picker-search');
+ waitForState($page, '@drive-picker-search', 'element === document.activeElement');
expect($page->script('document.activeElement?.dataset?.testid ?? null'))->toBe('drive-picker-search')
->and($page->script('getComputedStyle(document.body).pointerEvents'))->not->toBe('none');
@@ -488,7 +459,7 @@ test('the drive picker can be clicked, focused and typed in over the composer di
$page->assertPresent('@post-composer-dialog');
$page->script('window.__drive.finish()');
- waitForComposerMediaSourcesTestId($page, 'composer-media-item');
+ waitFor($page, '@composer-media-item');
$page->assertPresent('@post-composer-dialog')
->assertPresent('@composer-media-item')
@@ -503,7 +474,7 @@ test('a failed google drive sign-in opens no picker and shows the popup message'
enableOnlyGoogleDriveForMediaSources();
$page = openComposerForMediaSources($this);
- waitForComposerMediaSourcesTestId($page, 'composer-base-media-source-menu');
+ waitFor($page, '@composer-base-media-source-menu');
stubGoogleDriveForMediaSources($page);
chooseComposerMediaSource($page, 'composer-base', 'google_drive');
$nonce = googleDriveSignInNonce($page);
@@ -516,7 +487,7 @@ test('a failed google drive sign-in opens no picker and shows the popup message'
}));
true;
JS);
- waitForComposerMediaSourcesCondition($page, "document.body.innerText.includes('TryPost needs access to the file you pick')");
+ waitForCondition($page, "document.body.innerText.includes('TryPost needs access to the file you pick')");
$page->assertSee($message)
->assertNotPresent('@composer-media-item')
@@ -538,18 +509,18 @@ test('the real sign-in popup, start to callback, hands the drive token to the co
]);
$page = openComposerForMediaSources($this);
- waitForComposerMediaSourcesTestId($page, 'composer-base-media-source-menu');
+ waitFor($page, '@composer-base-media-source-menu');
stubGoogleDriveForMediaSources($page);
$page->script('window.open = (url) => { window.__drive.opened.push(url); window.__drive.openedInClick = window.__drive.inClick; return { closed: true, close() {} }; }; true;');
chooseComposerMediaSource($page, 'composer-base', 'google_drive');
$opened = $page->script('window.__drive.opened[0]');
$popup = visit($opened);
- waitForComposerMediaSourcesTestId($popup, 'media-source-popup');
+ waitFor($popup, '@media-source-popup');
$popup->assertAttribute('@media-source-popup', 'data-success', 'true')
->assertSee(__('integrations.media_source_popup.google_drive_ready'));
- waitForComposerMediaSourcesTestId($page, 'composer-media-item', rounds: 4);
+ waitFor($page, '@composer-media-item');
$page->assertPresent('@composer-media-item')
->assertNoJavaScriptErrors();
@@ -562,13 +533,13 @@ test('opening the media sources menu preloads the picker sdk only', function ()
config()->set('trypost.media_sources.google_drive.picker_sdk', 'data:text/javascript,window.__pickerLoaded=true');
$page = openComposerForMediaSources($this);
- waitForComposerMediaSourcesTestId($page, 'composer-base-media-source-menu');
+ waitFor($page, '@composer-base-media-source-menu');
expect($page->script('window.__pickerLoaded ?? false'))->toBeFalse();
$page->click('@composer-base-media-source-menu');
- waitForComposerMediaSourcesTestId($page, 'media-source-google_drive');
- waitForComposerMediaSourcesCondition($page, 'window.__pickerLoaded === true');
+ waitFor($page, '@media-source-google_drive');
+ waitForCondition($page, 'window.__pickerLoaded === true');
expect($page->script('window.__pickerLoaded ?? false'))->toBeTrue()
->and($page->script("[...document.scripts].some((script) => script.src.includes('accounts.google.com'))"))->toBeFalse();
diff --git a/tests/Browser/ComposerMediaTrayTest.php b/tests/Browser/ComposerMediaTrayTest.php
index 1dfb0bc26..83b7bcf9c 100644
--- a/tests/Browser/ComposerMediaTrayTest.php
+++ b/tests/Browser/ComposerMediaTrayTest.php
@@ -8,31 +8,6 @@ use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
-/**
- * Poll from the page until `$condition` holds (never sleep(): the test server
- * only ticks while Pest awaits Playwright).
- */
-function waitForComposerMediaTrayCondition(mixed $page, string $condition): void
-{
- $page->script(<<<JS
- (async () => {
- for (let attempt = 0; attempt < 300; attempt++) {
- if ({$condition}) return;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })();
- JS);
-}
-
-/**
- * Wait for a data-testid element to mount and lay out. Pest browser `@`
- * selectors resolve to data-testid, and assertions do not auto-wait on SPA paint.
- */
-function waitForComposerMediaTrayTestId(mixed $page, string $testId): void
-{
- waitForComposerMediaTrayCondition($page, "document.querySelector('[data-testid=\"{$testId}\"]')?.getBoundingClientRect().height > 0");
-}
-
function composerMediaTrayCount(mixed $page, string $testId): int
{
return (int) $page->script("document.querySelectorAll('[data-testid=\"{$testId}\"]').length");
@@ -64,19 +39,13 @@ function openComposerMediaTray(mixed $test, string $mode = 'pass', int $channels
$test->actingAs($user);
$page = visit(route('app.posts.create'));
- waitForComposerMediaTrayCondition($page, <<<'JS'
- (() => {
- const sheet = document.querySelector('[data-testid="post-composer-dialog"]');
- return sheet?.getAttribute('data-state') === 'open'
- && sheet.getAnimations().every((animation) => animation.playState !== 'running')
- && document.querySelector('[data-testid="composer-add-account"]')?.getBoundingClientRect().height > 0;
- })()
- JS);
+ waitForOpen($page, '@post-composer-dialog');
+ waitFor($page, '@composer-add-account');
if ($select) {
selectComposerMediaTrayChannels($page, $accounts);
}
$networks = collect($accounts)->pluck('platform')->unique()->count();
- waitForComposerMediaTrayTestId($page, $select && $networks === 1 ? "composer-{$accounts[0]->id}-dropzone" : 'composer-dropzone');
+ waitFor($page, $select && $networks === 1 ? "@composer-{$accounts[0]->id}-dropzone" : '@composer-dropzone');
$uploadUrl = route('app.media.store-chunked', absolute: false);
$page->script(<<<JS
@@ -173,7 +142,7 @@ test('the toolbar has no plus button and the channel dropzone opens its own file
->assertNotPresent('@composer-base-add-media');
selectComposerMediaTrayChannels($page, [$account]);
- waitForComposerMediaTrayTestId($page, "composer-{$account->id}-dropzone");
+ waitFor($page, "@composer-{$account->id}-dropzone");
$page->script(<<<JS
(() => {
window.__fileDialogOpened = 0;
@@ -192,17 +161,17 @@ test('each file gets an uploading tile and becomes a ready tile in the order it
[$page] = openComposerMediaTray($this, 'hold');
selectComposerMediaTrayFiles($page, '['.composerMediaTrayPng('first.png').', '.composerMediaTrayPng('second.png').']');
- waitForComposerMediaTrayCondition($page, 'window.__uploads.held.length === 2');
+ waitForCondition($page, 'window.__uploads.held.length === 2');
expect(composerMediaTrayCount($page, 'composer-upload-item'))->toBe(2)
->and(composerMediaTrayCount($page, 'composer-media-item'))->toBe(0);
$page->script("window.__releaseUpload('second.png')");
- waitForComposerMediaTrayCondition($page, "document.querySelectorAll('[data-testid=\"composer-upload-item\"]')[1]?.querySelector('[role=\"progressbar\"]')?.getAttribute('aria-valuenow') === '100'");
+ waitForCondition($page, "document.querySelectorAll('[data-testid=\"composer-upload-item\"]')[1]?.querySelector('[role=\"progressbar\"]')?.getAttribute('aria-valuenow') === '100'");
expect(composerMediaTrayCount($page, 'composer-media-item'))->toBe(0)
->and(composerMediaTrayCount($page, 'composer-upload-item'))->toBe(2);
$page->script("window.__releaseUpload('first.png')");
- waitForComposerMediaTrayCondition($page, "document.querySelectorAll('[data-testid=\"composer-media-item\"]').length === 2");
+ waitForCount($page, '@composer-media-item', 2);
$sources = $page->script("[...document.querySelectorAll('[data-testid=\"composer-media-item\"] img')].map((image) => image.getAttribute('src'))");
$uploads = Media::where('collection', Media::COLLECTION_UPLOADS)->get()->keyBy('original_filename');
@@ -215,12 +184,12 @@ test('no more than three files upload at once', function () {
[$page] = openComposerMediaTray($this, 'hold');
selectComposerMediaTrayFiles($page, '['.implode(', ', array_map(composerMediaTrayPng(...), ['a.png', 'b.png', 'c.png', 'd.png'])).']');
- waitForComposerMediaTrayCondition($page, 'window.__uploads.held.length === 3');
+ waitForCondition($page, 'window.__uploads.held.length === 3');
expect($page->script('window.__uploads.held.map((held) => held.name)'))->toBe(['a.png', 'b.png', 'c.png'])
->and(composerMediaTrayCount($page, 'composer-upload-item'))->toBe(4);
$page->script("window.__releaseUpload('a.png')");
- waitForComposerMediaTrayCondition($page, "window.__uploads.held.some((held) => held.name === 'd.png')");
+ waitForCondition($page, "window.__uploads.held.some((held) => held.name === 'd.png')");
expect($page->script('window.__uploads.held.map((held) => held.name)'))->toBe(['b.png', 'c.png', 'd.png']);
$page->assertNoJavaScriptErrors();
});
@@ -229,7 +198,7 @@ test('an unsupported file type becomes an error tile and is never sent', functio
[$page] = openComposerMediaTray($this);
selectComposerMediaTrayFiles($page, "[new File(['hello'], 'notes.txt', { type: 'text/plain' })]");
- waitForComposerMediaTrayTestId($page, 'composer-upload-error');
+ waitFor($page, '@composer-upload-error');
expect($page->script('document.querySelector(\'[data-testid="composer-upload-error"]\').dataset.reason'))->toBe('unsupported_type')
->and($page->script('window.__uploads.count'))->toBe(0);
@@ -243,18 +212,18 @@ test('saving is blocked while an upload is in flight and the finished upload is
$page->fill('@composer-base-content', 'Post with an upload');
selectComposerMediaTrayFiles($page, '['.composerMediaTrayPng('in-flight.png').']');
- waitForComposerMediaTrayCondition($page, 'window.__uploads.held.length === 1');
+ waitForCondition($page, 'window.__uploads.held.length === 1');
expect(composerMediaTrayDisabled($page, 'composer-save-draft'))->toBeTrue();
selectComposerMediaTrayChannels($page, [$account]);
- waitForComposerMediaTrayTestId($page, 'composer-submit');
+ waitFor($page, '@composer-submit');
expect(composerMediaTrayDisabled($page, 'composer-submit'))->toBeTrue()
->and(composerMediaTrayDisabled($page, 'composer-save-draft'))->toBeTrue();
$page->script("window.__releaseUpload('in-flight.png')");
- waitForComposerMediaTrayCondition($page, "document.querySelector('[data-testid=\"composer-save-draft\"]')?.disabled === false");
+ waitForState($page, '@composer-save-draft', 'element.disabled === false');
expect(composerMediaTrayDisabled($page, 'composer-submit'))->toBeFalse();
$page->click('@composer-save-draft');
- waitForComposerMediaTrayCondition($page, "!document.querySelector('[data-testid=\"post-composer-dialog\"]')");
+ waitForGone($page, '@post-composer-dialog');
$post = Post::where('workspace_id', $workspace->id)->sole();
$owned = $post->ownedMedia()->sole();
@@ -269,7 +238,7 @@ test('cancel removes an uploading tile and retry recovers a network failure', fu
[$page] = openComposerMediaTray($this, 'hold', platform: ['instagram', 'threads'], select: true);
selectComposerMediaTrayFiles($page, '['.composerMediaTrayPng('cancel-me.png').']');
- waitForComposerMediaTrayCondition($page, 'window.__uploads.held.length === 1');
+ waitForCondition($page, 'window.__uploads.held.length === 1');
$page->click('@composer-upload-cancel-0')
->assertMissing('@composer-upload-item')
->assertMissing('@composer-media-item');
@@ -277,11 +246,11 @@ test('cancel removes an uploading tile and retry recovers a network failure', fu
$page->script("window.__uploads.mode = 'pass'; window.__uploads.failNext = true;");
selectComposerMediaTrayFiles($page, '['.composerMediaTrayPng('retry-me.png').']');
- waitForComposerMediaTrayTestId($page, 'composer-upload-error');
+ waitFor($page, '@composer-upload-error');
expect($page->script('document.querySelector(\'[data-testid="composer-upload-error"]\').dataset.reason'))->toBe('network');
$page->click('@composer-upload-retry-0');
- waitForComposerMediaTrayTestId($page, 'composer-media-item');
+ waitFor($page, '@composer-media-item');
$page->assertMissing('@composer-upload-error')
->assertNoJavaScriptErrors();
expect(Media::where('collection', Media::COLLECTION_UPLOADS)->pluck('original_filename')->all())->toBe(['retry-me.png']);
@@ -292,7 +261,7 @@ test('a rejected upload shows the server message without Retry', function () {
$page->script("window.__uploads.rejectNext = 'This HEIC file could not be read.'");
selectComposerMediaTrayFiles($page, '['.composerMediaTrayPng('rejected.png').']');
- waitForComposerMediaTrayTestId($page, 'composer-upload-error');
+ waitFor($page, '@composer-upload-error');
expect($page->script('document.querySelector(\'[data-testid="composer-upload-error"]\').dataset.reason'))->toBe('rejected');
$page->assertSeeIn('@composer-upload-error', 'This HEIC file could not be read.')
@@ -305,31 +274,31 @@ test('three uploads run at once across the shared and channel trays, and uploads
$second = $accounts[1];
selectComposerMediaTrayFiles($page, '['.composerMediaTrayPng('shared-a.png').', '.composerMediaTrayPng('shared-b.png').']');
- waitForComposerMediaTrayCondition($page, 'window.__uploads.held.length === 2');
+ waitForCondition($page, 'window.__uploads.held.length === 2');
$page->click('@composer-next');
- waitForComposerMediaTrayTestId($page, "composer-{$first->id}-dropzone");
+ waitFor($page, "@composer-{$first->id}-dropzone");
selectComposerMediaTrayFiles($page, '['.composerMediaTrayPng('channel-c.png').', '.composerMediaTrayPng('channel-d.png').']', "composer-{$first->id}");
- waitForComposerMediaTrayCondition($page, 'window.__uploads.held.length === 3');
+ waitForCondition($page, 'window.__uploads.held.length === 3');
expect($page->script('window.__uploads.held.map((held) => held.name)'))->toBe(['shared-a.png', 'shared-b.png', 'channel-c.png'])
->and(composerMediaTrayCount($page, "composer-{$first->id}-upload-item"))->toBe(4);
$page->click("@composer-account-{$second->id}");
- waitForComposerMediaTrayTestId($page, "composer-{$second->id}-dropzone");
+ waitFor($page, "@composer-{$second->id}-dropzone");
$page->script("window.__releaseUpload('shared-a.png'); window.__releaseUpload('shared-b.png');");
- waitForComposerMediaTrayCondition($page, "document.querySelectorAll('[data-testid=\"composer-{$second->id}-media-item\"]').length === 2 && window.__uploads.held.length === 2");
+ waitForCondition($page, "document.querySelectorAll('[data-testid=\"composer-{$second->id}-media-item\"]').length === 2 && window.__uploads.held.length === 2");
$page->script("window.__releaseUpload('channel-c.png'); window.__releaseUpload('channel-d.png');");
- waitForComposerMediaTrayCondition($page, 'window.__uploads.held.length === 0');
+ waitForCondition($page, 'window.__uploads.held.length === 0');
$page->click("@composer-account-{$first->id}");
- waitForComposerMediaTrayCondition($page, "document.querySelectorAll('[data-testid=\"composer-{$first->id}-media-item\"]').length === 4");
+ waitForCount($page, "@composer-{$first->id}-media-item", 4);
expect(composerMediaTrayCount($page, "composer-{$first->id}-media-item"))->toBe(4)
->and(composerMediaTrayCount($page, "composer-{$second->id}-media-item"))->toBe(0);
$page->click('@composer-back');
- waitForComposerMediaTrayTestId($page, 'composer-back-confirm-go');
+ waitFor($page, '@composer-back-confirm-go');
$page->click('@composer-back-confirm-go');
- waitForComposerMediaTrayTestId($page, 'composer-media-item');
+ waitFor($page, '@composer-media-item');
expect(composerMediaTrayCount($page, 'composer-media-item'))->toBe(2)
->and(composerMediaTrayDisabled($page, 'composer-save-draft'))->toBeFalse();
$page->assertNoJavaScriptErrors();
@@ -339,9 +308,9 @@ test('closing the composer aborts uploads still in flight', function () {
[$page] = openComposerMediaTray($this, 'hold');
selectComposerMediaTrayFiles($page, '['.composerMediaTrayPng('left-behind.png').']');
- waitForComposerMediaTrayCondition($page, 'window.__uploads.held.length === 1');
+ waitForCondition($page, 'window.__uploads.held.length === 1');
$page->click('@composer-close');
- waitForComposerMediaTrayCondition($page, '!document.querySelector(\'[data-testid="post-composer-dialog"]\')');
+ waitForGone($page, '@post-composer-dialog');
expect($page->script('window.__uploads.aborted'))->toBe(1)
->and(Media::count())->toBe(0);
@@ -353,21 +322,21 @@ test('an expired upload is reported on its tile in the shared tray and in a chan
$page->fill('@composer-base-content', 'Expired upload');
selectComposerMediaTrayFiles($page, '['.composerMediaTrayPng('shared-expired.png').']');
- waitForComposerMediaTrayTestId($page, 'composer-media-item');
+ waitFor($page, '@composer-media-item');
Media::where('original_filename', 'shared-expired.png')->delete();
$page->click('@composer-save-draft');
- waitForComposerMediaTrayTestId($page, 'composer-media-error-0');
+ waitFor($page, '@composer-media-error-0');
$page->assertSeeIn('@composer-media-error-0', 'This upload expired. Add the file again.')
->click('@composer-remove-0')
->assertMissing('@composer-media-error-0');
$page->click('@composer-next');
- waitForComposerMediaTrayTestId($page, "composer-{$account->id}-dropzone");
+ waitFor($page, "@composer-{$account->id}-dropzone");
selectComposerMediaTrayFiles($page, '['.composerMediaTrayPng('channel-expired.png').']', "composer-{$account->id}");
- waitForComposerMediaTrayTestId($page, "composer-{$account->id}-media-item");
+ waitFor($page, "@composer-{$account->id}-media-item");
Media::where('original_filename', 'channel-expired.png')->delete();
$page->click('@composer-save-draft');
- waitForComposerMediaTrayTestId($page, "composer-{$account->id}-media-error-0");
+ waitFor($page, "@composer-{$account->id}-media-error-0");
$page->assertSeeIn("@composer-{$account->id}-media-error-0", 'This upload expired. Add the file again.')
->assertNoJavaScriptErrors();
expect(Post::count())->toBe(0);
@@ -382,7 +351,7 @@ function uploadComposerMediaTrayTiles(mixed $page, array $names): void
{
selectComposerMediaTrayFiles($page, '['.implode(', ', array_map(composerMediaTrayPng(...), $names)).']');
$count = count($names);
- waitForComposerMediaTrayCondition($page, "document.querySelectorAll('[data-testid=\"composer-media-item\"]').length === {$count}");
+ waitForCount($page, '@composer-media-item', $count);
}
/**
@@ -400,17 +369,17 @@ test('dragging a tile before another reorders the tray and the save keeps the or
[$page, $workspace, $account] = openComposerMediaTray($this);
$page->fill('@composer-base-content', 'Reordered media');
uploadComposerMediaTrayTiles($page, ['first.png', 'second.png']);
- waitForComposerMediaTrayTestId($page, 'composer-media-item-1');
+ waitFor($page, '@composer-media-item-1');
$second = $page->script("document.querySelectorAll('[data-testid=\"composer-media-item\"] img')[1].getAttribute('src')");
$page->drag('@composer-drag-handle-1', '@composer-media-item-0');
- waitForComposerMediaTrayCondition($page, "document.querySelector('[data-testid=\"composer-media-item\"] img')?.getAttribute('src') === '{$second}'");
+ waitForState($page, '@composer-media-item img', "element.getAttribute('src') === '{$second}'");
expect(composerMediaTrayOrder($page))->toBe(['second.png', 'first.png']);
selectComposerMediaTrayChannels($page, [$account]);
$page->click('@composer-save-draft');
- waitForComposerMediaTrayCondition($page, "!document.querySelector('[data-testid=\"post-composer-dialog\"]')");
+ waitForGone($page, '@post-composer-dialog');
$post = Post::where('workspace_id', $workspace->id)->sole();
$owned = $post->ownedMedia()->get()->keyBy('id');
@@ -423,7 +392,7 @@ test('arrow keys on the drag handle move the tile, keep focus on its handle and
uploadComposerMediaTrayTiles($page, ['first.png', 'second.png']);
$page->keys('@composer-drag-handle-0', 'ArrowRight');
- waitForComposerMediaTrayCondition($page, "document.activeElement?.dataset.testid === 'composer-drag-handle-1'");
+ waitForState($page, '@composer-drag-handle-1', 'element === document.activeElement');
expect(composerMediaTrayOrder($page))->toBe(['second.png', 'first.png'])
->and($page->script('document.activeElement?.dataset.testid'))->toBe('composer-drag-handle-1')
@@ -435,7 +404,7 @@ test('arrow keys on the drag handle move the tile, keep focus on its handle and
->and($page->script('document.activeElement?.dataset.testid'))->toBe('composer-drag-handle-1');
$page->keys('@composer-drag-handle-1', 'ArrowLeft');
- waitForComposerMediaTrayCondition($page, "document.activeElement?.dataset.testid === 'composer-drag-handle-0'");
+ waitForState($page, '@composer-drag-handle-0', 'element === document.activeElement');
expect(composerMediaTrayOrder($page))->toBe(['first.png', 'second.png']);
$page->assertNoJavaScriptErrors();
});
@@ -447,7 +416,7 @@ test('a tile is dragged only by its handle and a single tile has no handle', fun
expect($page->script("getComputedStyle(document.querySelector('[data-testid=\"composer-drag-handle-0\"]')).display"))->toBe('none');
selectComposerMediaTrayFiles($page, '['.composerMediaTrayPng('second.png').']');
- waitForComposerMediaTrayCondition($page, "document.querySelectorAll('[data-testid=\"composer-media-item\"]').length === 2");
+ waitForCount($page, '@composer-media-item', 2);
$page->script(<<<'JS'
(() => {
const source = document.querySelector('[data-testid="composer-media-item-1"]');
@@ -484,7 +453,7 @@ test('pasting an image into the post content adds an upload and leaves text past
[$page] = openComposerMediaTray($this);
expect(pasteIntoComposerMediaTray($page, 'composer-base-content', '['.composerMediaTrayPng('pasted.png').']'))->toBeTrue();
- waitForComposerMediaTrayCondition($page, "document.querySelectorAll('[data-testid=\"composer-media-item\"]').length === 1");
+ waitForCount($page, '@composer-media-item', 1);
expect(pasteIntoComposerMediaTray($page, 'composer-base-content', '[]', 'hello'))->toBeFalse()
->and(composerMediaTrayCount($page, 'composer-media-item'))->toBe(1)
@@ -496,16 +465,16 @@ test('pasting an image into a channel caption adds it to that channel tray only'
[$page, , $account] = openComposerMediaTray($this, platform: ['instagram', 'threads'], select: true);
$page->fill('@composer-base-content', 'Shared text');
$page->click('@composer-next');
- waitForComposerMediaTrayTestId($page, "composer-caption-{$account->id}");
+ waitFor($page, "@composer-caption-{$account->id}");
expect(pasteIntoComposerMediaTray($page, "composer-caption-{$account->id}", '['.composerMediaTrayPng('channel.png').']'))->toBeTrue();
- waitForComposerMediaTrayCondition($page, "document.querySelectorAll('[data-testid=\"composer-{$account->id}-media-item\"]').length === 1");
+ waitForCount($page, "@composer-{$account->id}-media-item", 1);
expect(composerMediaTrayCount($page, "composer-{$account->id}-media-item"))->toBe(1);
$page->click('@composer-back');
- waitForComposerMediaTrayTestId($page, 'composer-back-confirm-go');
+ waitFor($page, '@composer-back-confirm-go');
$page->click('@composer-back-confirm-go');
- waitForComposerMediaTrayTestId($page, 'composer-dropzone');
+ waitFor($page, '@composer-dropzone');
expect(composerMediaTrayCount($page, 'composer-media-item'))->toBe(0);
$page->assertNoJavaScriptErrors();
});
@@ -515,15 +484,15 @@ test('deselecting a channel aborts its uploads, unblocks saving and leaves nothi
$second = $accounts[1];
$page->fill('@composer-base-content', 'Deselect mid-upload');
$page->click('@composer-next');
- waitForComposerMediaTrayTestId($page, "composer-{$first->id}-dropzone");
+ waitFor($page, "@composer-{$first->id}-dropzone");
selectComposerMediaTrayFiles($page, '['.composerMediaTrayPng('held-channel.png').", new File(['x'], 'notes.txt', { type: 'text/plain' })]", "composer-{$first->id}");
- waitForComposerMediaTrayCondition($page, 'window.__uploads.held.length === 1');
+ waitForCondition($page, 'window.__uploads.held.length === 1');
expect(composerMediaTrayCount($page, "composer-{$first->id}-upload-error"))->toBe(1)
->and(composerMediaTrayDisabled($page, 'composer-save-draft'))->toBeTrue();
$page->click("@composer-remove-account-{$first->id}");
- waitForComposerMediaTrayTestId($page, "composer-{$second->id}-dropzone");
+ waitFor($page, "@composer-{$second->id}-dropzone");
expect($page->script('window.__uploads.aborted'))->toBe(1)
->and(composerMediaTrayDisabled($page, 'composer-save-draft'))->toBeFalse();
$page->assertMissing('@composer-upload-blocked');
@@ -531,7 +500,7 @@ test('deselecting a channel aborts its uploads, unblocks saving and leaves nothi
$page->click('@composer-add-account')->click("@composer-account-option-{$first->id}");
$page->click('@composer-next');
$page->click("@composer-account-{$first->id}");
- waitForComposerMediaTrayTestId($page, "composer-{$first->id}-dropzone");
+ waitFor($page, "@composer-{$first->id}-dropzone");
expect(composerMediaTrayCount($page, "composer-{$first->id}-upload-error"))->toBe(0)
->and(composerMediaTrayCount($page, "composer-{$first->id}-upload-item"))->toBe(0)
->and(composerMediaTrayDisabled($page, 'composer-save-draft'))->toBeFalse()
@@ -544,18 +513,18 @@ test('a server error follows the expired item when an earlier item is removed',
$page->fill('@composer-base-content', 'Two uploads, one expired');
selectComposerMediaTrayFiles($page, '['.composerMediaTrayPng('kept.png').', '.composerMediaTrayPng('expired.png').']');
- waitForComposerMediaTrayCondition($page, "document.querySelectorAll('[data-testid=\"composer-media-item\"]').length === 2");
+ waitForCount($page, '@composer-media-item', 2);
$expired = Media::where('original_filename', 'expired.png')->sole();
$expiredUrl = $expired->url;
$expired->delete();
$page->click('@composer-save-draft');
- waitForComposerMediaTrayTestId($page, 'composer-media-error-1');
+ waitFor($page, '@composer-media-error-1');
$page->assertMissing('@composer-media-error-0');
$page->click('@composer-remove-0');
- waitForComposerMediaTrayCondition($page, "document.querySelectorAll('[data-testid=\"composer-media-item\"]').length === 1");
- waitForComposerMediaTrayTestId($page, 'composer-media-error-0');
+ waitForCount($page, '@composer-media-item', 1);
+ waitFor($page, '@composer-media-error-0');
expect($page->script("document.querySelector('[data-testid=\"composer-media-item\"] img').getAttribute('src')"))->toBe($expiredUrl);
$page->assertSeeIn('@composer-media-error-0', 'This upload expired. Add the file again.')
->assertMissing('@composer-media-error-1')
@@ -571,14 +540,14 @@ test('a server error follows the expired item when an earlier item is removed',
function removeComposerMediaTrayInstagramImage(mixed $test): array
{
[$page, , $account] = openComposerMediaTray($test, platform: 'instagram', select: true);
- waitForComposerMediaTrayTestId($page, "composer-media-warning-{$account->id}");
+ waitFor($page, "@composer-media-warning-{$account->id}");
selectComposerMediaTrayFiles($page, '['.composerMediaTrayPng('beach.png').']', "composer-{$account->id}");
- waitForComposerMediaTrayCondition($page, "document.querySelectorAll('[data-testid=\"composer-{$account->id}-media-item\"]').length === 1");
+ waitForCount($page, "@composer-{$account->id}-media-item", 1);
$page->assertMissing("@composer-media-warning-{$account->id}")
->assertMissing("@composer-{$account->id}-suggested-media")
->click("@composer-{$account->id}-remove-0");
- waitForComposerMediaTrayTestId($page, "composer-{$account->id}-suggested-0");
+ waitFor($page, "@composer-{$account->id}-suggested-0");
return [$page, $account];
}
@@ -592,9 +561,9 @@ test('dismissing suggested media hides the panel until the next removal', functi
->assertVisible("@composer-media-warning-{$account->id}");
selectComposerMediaTrayFiles($page, '['.composerMediaTrayPng('pier.png').']', "composer-{$account->id}");
- waitForComposerMediaTrayCondition($page, "document.querySelectorAll('[data-testid=\"composer-{$account->id}-media-item\"]').length === 1");
+ waitForCount($page, "@composer-{$account->id}-media-item", 1);
$page->click("@composer-{$account->id}-remove-0");
- waitForComposerMediaTrayTestId($page, "composer-{$account->id}-suggested-0");
+ waitFor($page, "@composer-{$account->id}-suggested-0");
expect(composerMediaTrayCount($page, "composer-{$account->id}-suggested-1"))->toBe(0);
$page->assertNoJavaScriptErrors();
@@ -610,7 +579,7 @@ function openComposerMediaTrayBlockedSubmit(mixed $test): array
{
[$page, , $account] = openComposerMediaTray($test, platform: 'instagram', select: true);
- waitForComposerMediaTrayTestId($page, "composer-media-warning-{$account->id}");
+ waitFor($page, "@composer-media-warning-{$account->id}");
expect($page->script("document.querySelector('[data-testid=\"composer-submit\"]').getAttribute('aria-disabled')"))->toBe('true');
$page->assertDisabled('@composer-submit');
@@ -621,7 +590,7 @@ test('hovering the blocked primary button names the first issue and the channel'
[$page, $account] = openComposerMediaTrayBlockedSubmit($this);
$page->hover('@composer-submit');
- waitForComposerMediaTrayTestId($page, 'composer-blocked-tooltip');
+ waitFor($page, '@composer-blocked-tooltip');
$page->assertSeeIn('@composer-blocked-tooltip', "Please include an image or video. ({$account->display_name})")
->assertNoJavaScriptErrors();
@@ -631,26 +600,26 @@ test('an upload still running when customizing shows in every card and lands in
[$page, , $first, $accounts] = openComposerMediaTray($this, 'hold', platform: ['instagram', 'threads', 'linkedin']);
[, $second, $linkedin] = $accounts;
selectComposerMediaTrayChannels($page, [$first, $second]);
- waitForComposerMediaTrayTestId($page, 'composer-next');
+ waitFor($page, '@composer-next');
selectComposerMediaTrayFiles($page, '['.composerMediaTrayPng('in-flight.png').']');
- waitForComposerMediaTrayCondition($page, 'window.__uploads.held.length === 1');
+ waitForCondition($page, 'window.__uploads.held.length === 1');
$page->click('@composer-next');
- waitForComposerMediaTrayTestId($page, "composer-{$first->id}-upload-item");
+ waitFor($page, "@composer-{$first->id}-upload-item");
expect(composerMediaTrayDisabled($page, 'composer-save-draft'))->toBeTrue();
$page->click("@composer-account-{$second->id}");
- waitForComposerMediaTrayTestId($page, "composer-{$second->id}-upload-item");
+ waitFor($page, "@composer-{$second->id}-upload-item");
$page->click('@composer-add-account')
->click("@composer-account-option-{$linkedin->id}");
- waitForComposerMediaTrayTestId($page, "composer-{$linkedin->id}-upload-item");
+ waitFor($page, "@composer-{$linkedin->id}-upload-item");
$page->script("window.__releaseUpload('in-flight.png');");
- waitForComposerMediaTrayCondition($page, "document.querySelectorAll('[data-testid=\"composer-{$linkedin->id}-media-item\"]').length === 1");
+ waitForCount($page, "@composer-{$linkedin->id}-media-item", 1);
$page->assertMissing("@composer-{$linkedin->id}-upload-item")
->click("@composer-account-{$first->id}");
- waitForComposerMediaTrayTestId($page, "composer-{$first->id}-media-item");
+ waitFor($page, "@composer-{$first->id}-media-item");
expect(composerMediaTrayCount($page, "composer-{$first->id}-media-item"))->toBe(1)
->and(composerMediaTrayDisabled($page, 'composer-save-draft'))->toBeFalse();
$page->assertNoJavaScriptErrors();
@@ -660,13 +629,13 @@ test('an upload that failed before customizing shows in the cards and removing i
[$page, , $first] = openComposerMediaTray($this, 'fail-first', platform: ['instagram', 'threads'], select: true);
selectComposerMediaTrayFiles($page, '['.composerMediaTrayPng('failed-early.png').']');
- waitForComposerMediaTrayTestId($page, 'composer-upload-error');
+ waitFor($page, '@composer-upload-error');
$page->click('@composer-next');
- waitForComposerMediaTrayTestId($page, "composer-{$first->id}-upload-error");
+ waitFor($page, "@composer-{$first->id}-upload-error");
expect(composerMediaTrayDisabled($page, 'composer-save-draft'))->toBeTrue();
$page->click("@composer-{$first->id}-upload-remove-0");
- waitForComposerMediaTrayCondition($page, "!document.querySelector('[data-testid=\"composer-{$first->id}-upload-error\"]')");
+ waitForGone($page, "@composer-{$first->id}-upload-error");
expect(composerMediaTrayDisabled($page, 'composer-save-draft'))->toBeFalse();
$page->assertNoJavaScriptErrors();
@@ -677,36 +646,36 @@ test('in a single-network thread the toolbar upload and the reply tray add to th
$id = $account->id;
$page->fill("@composer-caption-{$id}", 'First tweet');
$page->click('@thread-start');
- waitForComposerMediaTrayTestId($page, 'thread-reply-0');
+ waitFor($page, '@thread-reply-0');
$page->fill('@thread-reply-0', 'Second tweet')
->keys('@thread-reply-0', 'Shift+Enter');
- waitForComposerMediaTrayTestId($page, 'thread-reply-1');
+ waitFor($page, '@thread-reply-1');
$page->fill('@thread-reply-1', 'Third tweet');
$page->script("HTMLInputElement.prototype.click = function () { if (this.type === 'file') { window.__filePicker = (window.__filePicker ?? 0) + 1; } }; true;");
$page->click("@composer-{$id}-media-source-menu");
- waitForComposerMediaTrayTestId($page, 'media-source-upload');
+ waitFor($page, '@media-source-upload');
$page->click('@media-source-upload');
- waitForComposerMediaTrayCondition($page, 'window.__filePicker === 1');
+ waitForCondition($page, 'window.__filePicker === 1');
selectComposerMediaTrayFiles($page, '['.composerMediaTrayPng('toolbar.png').']', 'composer-media-menu');
- waitForComposerMediaTrayCondition($page, 'window.__uploads.held.length === 1');
+ waitForCondition($page, 'window.__uploads.held.length === 1');
expect(composerMediaTrayDisabled($page, 'composer-submit'))->toBeTrue()
->and(composerMediaTrayDisabled($page, 'composer-save-draft'))->toBeTrue();
$page->script("window.__releaseUpload('toolbar.png')");
- waitForComposerMediaTrayTestId($page, "composer-{$id}-reply-1-media-item-0");
- waitForComposerMediaTrayCondition($page, "document.querySelector('[data-testid=\"composer-save-draft\"]')?.disabled === false");
+ waitFor($page, "@composer-{$id}-reply-1-media-item-0");
+ waitForState($page, '@composer-save-draft', 'element.disabled === false');
selectComposerMediaTrayFiles($page, '['.composerMediaTrayPng('reply-tray.png').']', "composer-{$id}-reply-1");
- waitForComposerMediaTrayCondition($page, 'window.__uploads.held.length === 1');
+ waitForCondition($page, 'window.__uploads.held.length === 1');
expect(composerMediaTrayDisabled($page, 'composer-submit'))->toBeTrue()
->and(composerMediaTrayDisabled($page, 'composer-save-draft'))->toBeTrue();
$page->script("window.__releaseUpload('reply-tray.png')");
- waitForComposerMediaTrayTestId($page, "composer-{$id}-reply-1-media-item-1");
- waitForComposerMediaTrayCondition($page, "document.querySelector('[data-testid=\"composer-save-draft\"]')?.disabled === false");
+ waitFor($page, "@composer-{$id}-reply-1-media-item-1");
+ waitForState($page, '@composer-save-draft', 'element.disabled === false');
expect(composerMediaTrayCount($page, "composer-{$id}-media-item"))->toBe(0)
->and(composerMediaTrayCount($page, "composer-{$id}-reply-1-media-item"))->toBe(2);
diff --git a/tests/Browser/ComposerMobileTest.php b/tests/Browser/ComposerMobileTest.php
index 98e4373ba..bdeb84915 100644
--- a/tests/Browser/ComposerMobileTest.php
+++ b/tests/Browser/ComposerMobileTest.php
@@ -27,71 +27,40 @@ function composerMobileWorkspace(): array
return [$user, $workspace];
}
-function waitForComposerMobileCondition(mixed $page, string $condition): void
-{
- $page->script(<<<JS
- (async () => {
- for (let attempt = 0; attempt < 200; attempt++) {
- if ({$condition}) return;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })();
- JS);
-}
-
-function waitForComposerMobileTestId(mixed $page, string $testId): void
-{
- waitForComposerMobileCondition($page, "document.querySelector('[data-testid=\"{$testId}\"]')?.getBoundingClientRect().height > 0");
-}
-
-function waitForComposerMobileSettled(mixed $page, string $testId): void
-{
- waitForComposerMobileCondition($page, "(() => {
- const element = document.querySelector('[data-testid=\"{$testId}\"]');
- return element?.getAttribute('data-state') === 'open'
- && element.getAnimations().every((animation) => animation.playState !== 'running');
- })()");
-}
-
-function waitForComposerMobileGone(mixed $page, string $testId): void
-{
- waitForComposerMobileCondition($page, "!document.querySelector('[data-testid=\"{$testId}\"]')");
-}
-
function openComposerMobile(mixed $test, User $user, int $width, int $height): mixed
{
$test->actingAs($user);
$page = visit(route('app.posts.create'))->resize($width, $height);
- waitForComposerMobileSettled($page, 'post-composer-dialog');
- waitForComposerMobileTestId($page, 'composer-add-account');
+ waitForOpen($page, '@post-composer-dialog');
+ waitFor($page, '@composer-add-account');
return $page;
}
function openComposerMobileNetworkCard(mixed $page, SocialAccount $account): void
{
- waitForComposerMobileCondition($page, "document.querySelector('[data-testid=\"composer-caption-{$account->id}\"]') || document.querySelector('[data-testid=\"composer-expand-{$account->id}\"]')");
+ waitForState($page, "@composer-caption-{$account->id}, @composer-expand-{$account->id}", 'true');
if (! $page->script("!!document.querySelector('[data-testid=\"composer-caption-{$account->id}\"]')")) {
$page->click("@composer-expand-{$account->id}");
}
- waitForComposerMobileTestId($page, "composer-caption-{$account->id}");
+ waitFor($page, "@composer-caption-{$account->id}");
}
function selectComposerMobileChannel(mixed $page, SocialAccount $account): void
{
$page->click('@composer-add-account');
- waitForComposerMobileTestId($page, "composer-account-option-{$account->id}");
+ waitFor($page, "@composer-account-option-{$account->id}");
$page->click("@composer-account-option-{$account->id}")->click('@composer-add-account');
- waitForComposerMobileGone($page, "composer-account-option-{$account->id}");
- waitForComposerMobileTestId($page, "composer-account-{$account->id}");
+ waitForGone($page, "@composer-account-option-{$account->id}");
+ waitFor($page, "@composer-account-{$account->id}");
}
function selectAllComposerMobileChannels(mixed $page): void
{
$page->click('@composer-add-account');
- waitForComposerMobileTestId($page, 'composer-select-all');
+ waitFor($page, '@composer-select-all');
$page->click('@composer-select-all')->click('@composer-add-account');
- waitForComposerMobileGone($page, 'composer-select-all');
+ waitForGone($page, '@composer-select-all');
}
/**
@@ -192,16 +161,16 @@ test('below lg the edit and preview control switches between the editor and the
$page = openComposerMobile($this, $user, 390, 844);
selectComposerMobileChannel($page, $account);
- waitForComposerMobileTestId($page, "composer-caption-{$account->id}");
+ waitFor($page, "@composer-caption-{$account->id}");
$page->fill("@composer-caption-{$account->id}", 'Seen in the preview')
->click('@composer-view-preview');
- waitForComposerMobileTestId($page, 'composer-preview-frame');
+ waitFor($page, '@composer-preview-frame');
$page->assertVisible('@composer-preview-frame')
->assertMissing("@composer-caption-{$account->id}")
->assertAttribute('@composer-view-preview', 'aria-pressed', 'true')
->click('@composer-view-edit');
- waitForComposerMobileTestId($page, "composer-caption-{$account->id}");
+ waitFor($page, "@composer-caption-{$account->id}");
$page->assertValue("@composer-caption-{$account->id}", 'Seen in the preview')
->assertMissing('@composer-preview-frame')
@@ -217,7 +186,7 @@ test('below lg templates and the assistant open as a bottom sheet and closing ke
foreach (['templates' => 'composer-templates-toggle', 'assistant' => 'composer-ai-assistant'] as $panel => $toggle) {
$page->click("@{$toggle}");
- waitForComposerMobileSettled($page, "composer-{$panel}-sheet");
+ waitForOpen($page, "@composer-{$panel}-sheet");
$sheet = composerMobileRect($page, "composer-{$panel}-sheet");
expect(abs($sheet['bottom'] - $sheet['viewportHeight']))->toBeLessThan(2)
@@ -226,7 +195,7 @@ test('below lg templates and the assistant open as a bottom sheet and closing ke
->and($page->script("!!document.querySelector('[data-testid=\"composer-{$panel}-sheet\"] [data-testid=\"composer-{$panel}-panel\"]')"))->toBeTrue();
$page->assertAttribute("@{$toggle}", 'aria-pressed', 'true')
->click("@composer-{$panel}-sheet-close");
- waitForComposerMobileGone($page, "composer-{$panel}-sheet");
+ waitForGone($page, "@composer-{$panel}-sheet");
$page->assertValue('@composer-base-content', 'Keep this draft')
->assertAttribute("@{$toggle}", 'aria-pressed', 'false');
@@ -242,7 +211,7 @@ test('at 390px the schedule menu, date picker and labels open as bottom sheets i
$page = openComposerMobile($this, $user, 390, 844);
$page->click('@composer-schedule-trigger');
- waitForComposerMobileSettled($page, 'composer-schedule-sheet');
+ waitForOpen($page, '@composer-schedule-sheet');
$sheet = composerMobileRect($page, 'composer-schedule-sheet');
expect($sheet['top'])->toBeGreaterThanOrEqual(0)
@@ -253,7 +222,7 @@ test('at 390px the schedule menu, date picker and labels open as bottom sheets i
->and($page->script("document.querySelectorAll('[data-reka-popper-content-wrapper]').length"))->toBe(0);
$page->click('@composer-schedule-custom');
- waitForComposerMobileTestId($page, 'composer-schedule-picker');
+ waitFor($page, '@composer-schedule-picker');
$picker = $page->script(<<<'JS'
(() => {
@@ -274,11 +243,11 @@ test('at 390px the schedule menu, date picker and labels open as bottom sheets i
->and($picker['sheetTop'])->toBeGreaterThanOrEqual(0);
$page->click('@composer-schedule-done');
- waitForComposerMobileGone($page, 'composer-schedule-sheet');
+ waitForGone($page, '@composer-schedule-sheet');
$page->assertAttribute('@composer-submit', 'data-schedule-mode', 'custom');
$page->click('@composer-tags-trigger');
- waitForComposerMobileSettled($page, 'composer-label-sheet');
+ waitForOpen($page, '@composer-label-sheet');
$labels = composerMobileRect($page, 'composer-label-sheet');
expect($labels['top'])->toBeGreaterThanOrEqual(0)
@@ -286,7 +255,7 @@ test('at 390px the schedule menu, date picker and labels open as bottom sheets i
->and($page->script("!!document.querySelector('[data-testid=\"composer-label-sheet\"] [data-testid=\"composer-label-search\"]')"))->toBeTrue();
$page->click('@composer-label-close');
- waitForComposerMobileGone($page, 'composer-label-sheet');
+ waitForGone($page, '@composer-label-sheet');
$page->assertNoJavaScriptErrors();
});
@@ -296,8 +265,8 @@ test('touch devices get no tooltips in the composer', function () {
$this->actingAs($user);
$page = visit(route('app.posts.create'))->on()->mobile()->resize(390, 844);
- waitForComposerMobileSettled($page, 'post-composer-dialog');
- waitForComposerMobileTestId($page, 'composer-add-account');
+ waitForOpen($page, '@post-composer-dialog');
+ waitFor($page, '@composer-add-account');
expect($page->script("matchMedia('(hover: hover)').matches"))->toBeFalse();
@@ -306,7 +275,7 @@ test('touch devices get no tooltips in the composer', function () {
expect(composerMobileTooltipCount($page))->toBe(0);
$page->click('@composer-schedule-trigger');
- waitForComposerMobileSettled($page, 'composer-schedule-sheet');
+ waitForOpen($page, '@composer-schedule-sheet');
$page->hover('@composer-schedule-default-next');
expect(composerMobileTooltipCount($page))->toBe(0)
->and($page->script('getComputedStyle(document.querySelector(\'[data-testid="composer-schedule-default-now"]\')).opacity'))->toBe('1');
@@ -323,7 +292,7 @@ test('the open network card keeps its header pinned while its card scrolls', fun
selectAllComposerMobileChannels($page);
$page->fill('@composer-base-content', 'Sticky header')->click('@composer-next');
openComposerMobileNetworkCard($page, $instagram);
- waitForComposerMobileTestId($page, "composer-{$instagram->id}-header");
+ waitFor($page, "@composer-{$instagram->id}-header");
$pinned = $page->script(<<<JS
(async () => {
@@ -358,14 +327,14 @@ test('at 390px the footer is compact and the channel strip hints at hidden chips
$page = openComposerMobile($this, $user, 390, 844);
selectAllComposerMobileChannels($page);
- waitForComposerMobileCondition($page, "document.querySelector('[data-testid=\"composer-accounts\"]')?.hasAttribute('data-overflowing')");
+ waitForState($page, '@composer-accounts', "element.hasAttribute('data-overflowing')");
$footer = composerMobileRect($page, 'composer-footer');
expect($footer['height'])->toBeLessThanOrEqual(104)
->and($page->script("getComputedStyle(document.querySelector('[data-testid=\"composer-accounts\"]')).maskImage"))->toContain('linear-gradient');
$page->script("(() => { const strip = document.querySelector('[data-testid=\"composer-accounts\"]'); strip.scrollLeft = strip.scrollWidth; })()");
- waitForComposerMobileCondition($page, "!document.querySelector('[data-testid=\"composer-accounts\"]').hasAttribute('data-overflowing')");
+ waitForState($page, '@composer-accounts', "!element.hasAttribute('data-overflowing')");
expect($page->script("document.querySelector('[data-testid=\"composer-accounts\"]').hasAttribute('data-overflowing')"))->toBeFalse();
$page->assertNoJavaScriptErrors();
diff --git a/tests/Browser/ComposerNetworkCardsTest.php b/tests/Browser/ComposerNetworkCardsTest.php
index 3a31a656b..9c160b5a7 100644
--- a/tests/Browser/ComposerNetworkCardsTest.php
+++ b/tests/Browser/ComposerNetworkCardsTest.php
@@ -25,43 +25,12 @@ function networkCardsWorkspace(): array
return [$user, $workspace];
}
-function waitForNetworkCardsCondition(mixed $page, string $condition): void
-{
- $page->script(<<<JS
- (async () => {
- for (let attempt = 0; attempt < 300; attempt++) {
- const sheet = document.querySelector('[data-testid="post-composer-dialog"]');
- if (sheet?.getAttribute('data-state') === 'open'
- && sheet.getAnimations().every((animation) => animation.playState !== 'running')
- && ({$condition})) return;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })();
- JS);
-}
-
-function waitForNetworkCardsTestId(mixed $page, string $testId): void
-{
- waitForNetworkCardsCondition($page, "document.querySelector('[data-testid=\"{$testId}\"]')?.getBoundingClientRect().height > 0");
-}
-
-function waitForNetworkCardsClosed(mixed $page): void
-{
- $page->script(<<<'JS'
- (async () => {
- for (let attempt = 0; attempt < 300; attempt++) {
- if (!document.querySelector('[data-testid="post-composer-dialog"]')) return;
- await new Promise((resolve) => setTimeout(resolve, 100));
- }
- })();
- JS);
-}
-
function openNetworkCardsComposer(mixed $test, User $user): mixed
{
$test->actingAs($user);
$page = visit(route('app.posts.create'));
- waitForNetworkCardsTestId($page, 'composer-add-account');
+ waitForOpen($page, '@post-composer-dialog');
+ waitFor($page, '@composer-add-account');
return $page;
}
@@ -72,7 +41,8 @@ function openNetworkCardsComposer(mixed $test, User $user): mixed
function networkCardsAutosave(mixed $page, User $user, Workspace $workspace, string $condition): array
{
$snapshot = '('.browserStorageItemJs($user, 'composer.autosave', $workspace->id).')';
- waitForNetworkCardsCondition($page, str_replace('snapshot', $snapshot, $condition));
+ waitForOpen($page, '@post-composer-dialog');
+ waitForCondition($page, str_replace('snapshot', $snapshot, $condition));
return (array) $page->script($snapshot);
}
@@ -108,7 +78,8 @@ test('a second network keeps the shared step until customizing copies the text i
expect(networkCardsCaptionCount($page))->toBe(0);
$page->click('@composer-next');
- waitForNetworkCardsTestId($page, "composer-caption-{$x->id}");
+ waitForOpen($page, '@post-composer-dialog');
+ waitFor($page, "@composer-caption-{$x->id}");
$snapshot = networkCardsAutosave($page, $user, $workspace, "snapshot?.overrides?.['{$linkedin->id}']?.content !== undefined");
expect(data_get($snapshot, "overrides.{$x->id}.content"))->toBe('Draft for everyone')
@@ -121,14 +92,15 @@ test('a second network keeps the shared step until customizing copies the text i
->fill("@composer-caption-{$x->id}", 'Only on X')
->assertSeeIn("@composer-expand-{$linkedin->id}", 'Draft for everyone')
->click("@composer-expand-{$linkedin->id}");
- waitForNetworkCardsTestId($page, "composer-caption-{$linkedin->id}");
+ waitForOpen($page, '@post-composer-dialog');
+ waitFor($page, "@composer-caption-{$linkedin->id}");
$page->assertValue("@composer-caption-{$linkedin->id}", 'Draft for everyone')
->fill("@composer-caption-{$linkedin->id}", 'Only on LinkedIn')
->assertSeeIn("@composer-expand-{$x->id}", 'Only on X')
->assertNoJavaScriptErrors()
->click('@composer-save-draft');
- waitForNetworkCardsClosed($page);
+ waitForGone($page, '@post-composer-dialog');
expect(networkCardsSavedContents($workspace))->toEqual([
$x->id => 'Only on X',
@@ -152,7 +124,8 @@ test('a network added while customizing starts from the shared text', function (
->fill("@composer-caption-{$linkedin->id}", 'Edited on LinkedIn')
->click('@composer-add-account')
->click("@composer-account-option-{$facebook->id}");
- waitForNetworkCardsTestId($page, "composer-caption-{$facebook->id}");
+ waitForOpen($page, '@post-composer-dialog');
+ waitFor($page, "@composer-caption-{$facebook->id}");
expect(networkCardsCaptionCount($page))->toBe(1);
$page->assertValue("@composer-caption-{$facebook->id}", 'Shared start')
@@ -174,7 +147,8 @@ test('dropping back to one network keeps that network text as the post text', fu
->click("@composer-expand-{$linkedin->id}")
->fill("@composer-caption-{$linkedin->id}", 'LinkedIn only')
->click("@composer-remove-account-{$x->id}");
- waitForNetworkCardsCondition($page, "!document.querySelector('[data-testid=\"composer-account-{$x->id}\"]')");
+ waitForOpen($page, '@post-composer-dialog');
+ waitForGone($page, "@composer-account-{$x->id}");
$page->assertValue("@composer-caption-{$linkedin->id}", 'LinkedIn only')
->assertMissing("@composer-expand-{$linkedin->id}")
@@ -186,17 +160,19 @@ test('dropping back to one network keeps that network text as the post text', fu
->click("@composer-account-option-{$x->id}")
->assertValue('@composer-base-content', 'LinkedIn only')
->click('@composer-next');
- waitForNetworkCardsTestId($page, "composer-caption-{$x->id}");
+ waitForOpen($page, '@post-composer-dialog');
+ waitFor($page, "@composer-caption-{$x->id}");
$page->assertValue("@composer-caption-{$x->id}", 'LinkedIn only')
->fill("@composer-caption-{$x->id}", 'X only')
->click("@composer-remove-account-{$linkedin->id}");
- waitForNetworkCardsCondition($page, "!document.querySelector('[data-testid=\"composer-account-{$linkedin->id}\"]')");
+ waitForOpen($page, '@post-composer-dialog');
+ waitForGone($page, "@composer-account-{$linkedin->id}");
$page->assertValue("@composer-caption-{$x->id}", 'X only')
->assertMissing("@composer-expand-{$x->id}")
->assertNoJavaScriptErrors()
->click('@composer-save-draft');
- waitForNetworkCardsClosed($page);
+ waitForGone($page, '@post-composer-dialog');
expect(networkCardsSavedContents($workspace))->toEqual([$x->id => 'X only']);
});
@@ -208,7 +184,8 @@ test('two pages of one network share one card and still save one post each', fun
$page->click('@composer-add-account')
->click("@composer-account-option-{$first->id}")
->click("@composer-account-option-{$second->id}");
- waitForNetworkCardsTestId($page, "composer-caption-{$first->id}");
+ waitForOpen($page, '@post-composer-dialog');
+ waitFor($page, "@composer-caption-{$first->id}");
$page->assertMissing("@composer-caption-{$second->id}")
->assertMissing("@composer-expand-{$first->id}")
@@ -218,7 +195,7 @@ test('two pages of one network share one card and still save one post each', fun
->assertSeeIn('@composer-save-draft', 'Save drafts')
->assertNoJavaScriptErrors()
->click('@composer-save-draft');
- waitForNetworkCardsClosed($page);
+ waitForGone($page, '@post-composer-dialog');
expect(networkCardsSavedContents($workspace))->toEqual([
$first->id => 'Both pages',
@@ -248,13 +225,15 @@ test('cards and step one previews follow the channel list order and the preview
->toBe(['X', 'LinkedIn', 'Facebook']);
$page->assertSeeIn('@composer-preview-title', 'Post previews')
->click('@composer-next');
- waitForNetworkCardsTestId($page, "composer-caption-{$x->id}");
+ waitForOpen($page, '@post-composer-dialog');
+ waitFor($page, "@composer-caption-{$x->id}");
expect($page->script($order))->toBe(['open', $linkedin->id, $facebook->id]);
$page->assertSeeIn('@composer-preview-title', 'X preview')
->assertSeeIn('@composer-preview-frame', 'Ordered')
->click("@composer-expand-{$facebook->id}");
- waitForNetworkCardsTestId($page, "composer-caption-{$facebook->id}");
+ waitForOpen($page, '@post-composer-dialog');
+ waitFor($page, "@composer-caption-{$facebook->id}");
expect($page->script($order))->toBe([$x->id, $linkedin->id, 'open']);
$page->assertSeeIn('@composer-preview-title', 'Facebook preview')
@@ -278,15 +257,18 @@ test('two pinterest accounts in one card keep their own boards', function () {
->click('@composer-add-account')
->click("@composer-account-option-{$first->id}")
->click("@composer-account-option-{$second->id}");
- waitForNetworkCardsTestId($page, "composer-account-settings-{$second->id}");
+ waitForOpen($page, '@post-composer-dialog');
+ waitFor($page, "@composer-account-settings-{$second->id}");
$page->assertVisible("@composer-account-settings-{$first->id}");
$page->script("document.querySelector('[data-testid=\"composer-account-settings-{$second->id}\"] [data-testid=\"pinterest-board-trigger\"]').click()");
- waitForNetworkCardsTestId($page, 'pinterest-board-option-board_2');
+ waitForOpen($page, '@post-composer-dialog');
+ waitFor($page, '@pinterest-board-option-board_2');
$page->click('@pinterest-board-option-board_2');
- waitForNetworkCardsCondition($page, "!document.querySelector('[data-testid=\"pinterest-board-picker\"]')");
+ waitForOpen($page, '@post-composer-dialog');
+ waitForGone($page, '@pinterest-board-picker');
$page->assertNoJavaScriptErrors()->click('@composer-save-draft');
- waitForNetworkCardsClosed($page);
+ waitForGone($page, '@post-composer-dialog');
$boards = Post::query()->where('workspace_id', $workspace->id)->get()
->mapWithKeys(fn (Post $post): array => [$post->social_account_id => data_get($post->meta, 'board_id')]);
@@ -303,11 +285,13 @@ test('a story card hides its caption and keeps the text', function () {
->click("@composer-account-option-{$instagram->id}")
->fill("@composer-caption-{$instagram->id}", 'Kept for later')
->click("@composer-type-{$instagram->id}-instagram_story");
- waitForNetworkCardsCondition($page, "!document.querySelector('[data-testid=\"composer-caption-{$instagram->id}\"]')");
+ waitForOpen($page, '@post-composer-dialog');
+ waitForGone($page, "@composer-caption-{$instagram->id}");
$page->assertMissing("@composer-char-count-{$instagram->id}")
->click("@composer-type-{$instagram->id}-instagram_feed");
- waitForNetworkCardsTestId($page, "composer-caption-{$instagram->id}");
+ waitForOpen($page, '@post-composer-dialog');
+ waitFor($page, "@composer-caption-{$instagram->id}");
$page->assertValue("@composer-caption-{$instagram->id}", 'Kept for later')
->assertNoJavaScriptErrors();
});
@@ -325,15 +309,19 @@ test('going back drops a thread started on a network card', function () {
->click("@composer-account-{$bluesky->id}")
->assertMissing('@thread-start')
->click('@composer-next');
- waitForNetworkCardsTestId($page, 'thread-start');
+ waitForOpen($page, '@post-composer-dialog');
+ waitFor($page, '@thread-start');
$page->click('@thread-start');
- waitForNetworkCardsTestId($page, 'thread-reply-0');
+ waitForOpen($page, '@post-composer-dialog');
+ waitFor($page, '@thread-reply-0');
$page->fill('@thread-reply-0', 'A reply')
->click('@composer-back')
->click('@composer-back-confirm-go');
- waitForNetworkCardsTestId($page, 'composer-next');
+ waitForOpen($page, '@post-composer-dialog');
+ waitFor($page, '@composer-next');
$page->click('@composer-next');
- waitForNetworkCardsTestId($page, 'thread-start');
+ waitForOpen($page, '@post-composer-dialog');
+ waitFor($page, '@thread-start');
$page->assertMissing('@thread-replies')
->assertValue("@composer-caption-{$bluesky->id}", 'Shared text')
diff --git a/tests/Browser/ComposerPreviewTest.php b/tests/Browser/ComposerPreviewTest.php
index 5e6360a5e..5b9977371 100644
--- a/tests/Browser/ComposerPreviewTest.php
+++ b/tests/Browser/ComposerPreviewTest.php
@@ -9,21 +9,6 @@ use App\Models\Workspace;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str;
-function waitForComposerPreviewTestId(mixed $page, string $testId): void
-{
- $page->script(<<<JS
- (async () => {
- for (let attempt = 0; attempt < 100; attempt++) {
- const sheet = document.querySelector('[data-testid="post-composer-dialog"]');
- if (sheet?.getAttribute('data-state') === 'open'
- && sheet.getAnimations().every((animation) => animation.playState !== 'running')
- && document.querySelector('[data-testid="{$testId}"]')?.getBoundingClientRect().height > 0) return;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })();
- JS);
-}
-
/**
* @return array{0: User, 1: array<string, SocialAccount>}
*/
@@ -56,12 +41,14 @@ test('the preview panel lists one labelled card per network and renders each net
$this->actingAs($user);
$page = visit(route('app.posts.create'));
- waitForComposerPreviewTestId($page, 'composer-add-account');
+ waitForOpen($page, '@post-composer-dialog');
+ waitFor($page, '@composer-add-account');
$page->click('@composer-add-account')
->click('@composer-select-all')
->fill('@composer-base-content', 'Testing the preview https://trypost.it #hashtags');
- waitForComposerPreviewTestId($page, 'youtube-preview-subscribe');
+ waitForOpen($page, '@post-composer-dialog');
+ waitFor($page, '@youtube-preview-subscribe');
$page->assertSeeIn('@composer-preview-title', 'Post previews')
->assertPresent('@composer-preview-info');
@@ -95,7 +82,8 @@ test('the preview panel lists one labelled card per network and renders each net
expect($page->script('document.querySelectorAll("[data-testid=youtube-preview] [data-testid=preview-rail-action]").length'))->toBe(4);
$page->click('@composer-next');
- waitForComposerPreviewTestId($page, 'composer-customization');
+ waitForOpen($page, '@post-composer-dialog');
+ waitFor($page, '@composer-customization');
expect($page->script('document.querySelector("[data-testid=composer-preview-title]").textContent.trim()'))
->toMatch('/^(X|TikTok|Instagram|YouTube) preview$/')
@@ -117,7 +105,8 @@ test('a pdf preview crops the browser viewer frame around the page', function ()
$this->actingAs($user);
$page = visit(route('app.posts.edit', $post))->resize(1440, 900);
- waitForComposerPreviewTestId($page, 'linkedin-preview');
+ waitForOpen($page, '@post-composer-dialog');
+ waitFor($page, '@linkedin-preview');
$crop = $page->script(<<<'JS'
(() => {
@@ -156,7 +145,8 @@ test('the x preview lays two images side by side and three as one tall image bes
$this->actingAs($user);
$page = visit(route('app.posts.edit', $post))->resize(1440, 900);
- waitForComposerPreviewTestId($page, 'x-preview');
+ waitForOpen($page, '@post-composer-dialog');
+ waitFor($page, '@x-preview');
$tiles = $page->script(<<<'JS'
[...document.querySelectorAll('[data-testid="x-preview"] [data-testid="preview-media"] img')].map((image) => {
diff --git a/tests/Browser/ComposerQueueTest.php b/tests/Browser/ComposerQueueTest.php
index 8c3b032b8..eb136bb2d 100644
--- a/tests/Browser/ComposerQueueTest.php
+++ b/tests/Browser/ComposerQueueTest.php
@@ -16,49 +16,6 @@ use App\Models\Workspace;
use App\Support\PostingSchedule;
use Carbon\CarbonImmutable;
-/**
- * Poll from the page (never sleep()) until the composer dialog is open and
- * still and the given element is laid out.
- */
-function waitForComposerQueueTestId(mixed $page, string $testId): void
-{
- $page->script(<<<JS
- (async () => {
- for (let attempt = 0; attempt < 100; attempt++) {
- const sheet = document.querySelector('[data-testid="post-composer-dialog"]');
- if (sheet?.getAttribute('data-state') === 'open'
- && sheet.getAnimations().every((animation) => animation.playState !== 'running')
- && document.querySelector('[data-testid="{$testId}"]')?.getBoundingClientRect().height > 0) return;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })();
- JS);
-}
-
-function waitForComposerQueueClosed(mixed $page): void
-{
- $page->script(<<<'JS'
- (async () => {
- for (let attempt = 0; attempt < 100; attempt++) {
- if (!document.querySelector('[data-testid="post-composer-dialog"]')) return;
- await new Promise((resolve) => setTimeout(resolve, 100));
- }
- })();
- JS);
-}
-
-function waitForComposerQueuePageTestId(mixed $page, string $testId): void
-{
- $page->script(<<<JS
- (async () => {
- for (let attempt = 0; attempt < 100; attempt++) {
- if (document.querySelector('[data-testid="{$testId}"]')?.getBoundingClientRect().height > 0) return;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })();
- JS);
-}
-
/**
* @return array{0: User, 1: Workspace}
*/
@@ -131,7 +88,8 @@ function composerQueueSeedPost(User $user, Workspace $workspace, SocialAccount $
function composerQueueOpenWith(mixed $page, SocialAccount $channel): void
{
- waitForComposerQueueTestId($page, 'composer-add-account');
+ waitForOpen($page, '@post-composer-dialog');
+ waitFor($page, '@composer-add-account');
$page->click('@composer-add-account')
->click("@composer-account-option-{$channel->id}")
->fill("@composer-caption-{$channel->id}", 'Queued from the composer');
@@ -145,7 +103,8 @@ test('a channel with slots defaults to the queue and takes its first slot', func
$page = visit(route('app.posts.create'));
composerQueueOpenWith($page, $channel);
- waitForComposerQueueTestId($page, 'composer-submit');
+ waitForOpen($page, '@post-composer-dialog');
+ waitFor($page, '@composer-submit');
expect($page->script('document.querySelector("[data-testid=composer-submit]").dataset.scheduleMode'))->toBe('next')
->and($page->script('document.querySelector("[data-testid=composer-submit]").textContent.trim()'))->toBe('Add to queue');
@@ -157,7 +116,7 @@ test('a channel with slots defaults to the queue and takes its first slot', func
->assertMissing('@composer-queue-hint')
->click('@composer-schedule-next')
->click('@composer-submit');
- waitForComposerQueueClosed($page);
+ waitForGone($page, '@post-composer-dialog');
$post = Post::query()->where('workspace_id', $workspace->id)->sole();
@@ -176,7 +135,8 @@ test('the default posting action preference picks the composer initial mode', fu
$page = visit(route('app.posts.create'));
composerQueueOpenWith($page, $channel);
- waitForComposerQueueTestId($page, 'composer-submit');
+ waitForOpen($page, '@post-composer-dialog');
+ waitFor($page, '@composer-submit');
expect($page->script('document.querySelector("[data-testid=composer-submit]").dataset.scheduleMode'))->toBe($mode);
$page->assertNoJavaScriptErrors();
@@ -194,7 +154,8 @@ test('a queue default falls back when the channel has no posting times', functio
$page = visit(route('app.posts.create'));
composerQueueOpenWith($page, $channel);
- waitForComposerQueueTestId($page, 'composer-submit');
+ waitForOpen($page, '@post-composer-dialog');
+ waitFor($page, '@composer-submit');
expect($page->script('document.querySelector("[data-testid=composer-submit]").dataset.scheduleMode'))->toBe('now');
$page->assertNoJavaScriptErrors();
@@ -208,7 +169,7 @@ test('rapid star clicks keep only the last default posting action', function ()
$page = visit(route('app.posts.create'));
composerQueueOpenWith($page, $channel);
$page->click('@composer-schedule-trigger');
- waitForComposerQueuePageTestId($page, 'composer-schedule-default-now');
+ waitFor($page, '@composer-schedule-default-now');
$page->script(<<<'JS'
(() => {
@@ -232,15 +193,7 @@ test('rapid star clicks keep only the last default posting action', function ()
document.querySelector('[data-testid="composer-schedule-default-top"]').click();
})();
JS);
- $page->script(<<<'JS'
- (async () => {
- for (let attempt = 0; attempt < 100; attempt++) {
- const preferences = window.__preferences;
- if (preferences.last === 'top' && preferences.settled === preferences.started) return;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })();
- JS);
+ waitForCondition($page, "window.__preferences.last === 'top' && window.__preferences.settled === window.__preferences.started");
expect($page->script('window.__preferences.events'))->toBe(['start:now', 'end:now', 'start:top', 'end:top'])
->and($page->script('window.__preferences.last'))->toBe('top')
@@ -258,7 +211,7 @@ test('the star saves the default posting action without selecting the option', f
$page = visit(route('app.posts.create'));
composerQueueOpenWith($page, $channel);
$page->click('@composer-schedule-trigger');
- waitForComposerQueuePageTestId($page, 'composer-schedule-default-now');
+ waitFor($page, '@composer-schedule-default-now');
expect($page->script('document.querySelector("[data-testid=composer-schedule-default-next]").getAttribute("aria-pressed")'))->toBe('true')
->and($page->script('document.querySelector("[data-testid=composer-schedule-next]").getAttribute("aria-pressed")'))->toBe('true');
@@ -270,14 +223,7 @@ test('the star saves the default posting action without selecting the option', f
$page->hover('@composer-schedule-default-now')
->assertSee('Set as default posting action: Now.')
->click('@composer-schedule-default-now');
- $page->script(<<<'JS'
- (async () => {
- for (let attempt = 0; attempt < 100; attempt++) {
- if (performance.getEntriesByType('resource').some((entry) => entry.name.includes('/settings/preferences'))) return;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })();
- JS);
+ waitForCondition($page, "performance.getEntriesByType('resource').some((entry) => entry.name.includes('/settings/preferences'))");
expect($page->script('document.querySelector("[data-testid=composer-schedule-default-now]").getAttribute("aria-pressed")'))->toBe('true')
->and($page->script('document.querySelector("[data-testid=composer-schedule-default-next]").getAttribute("aria-pressed")'))->toBe('false')
@@ -307,11 +253,12 @@ test('prioritize puts the new post first and moves the queued one back', functio
$page->click('@composer-schedule-trigger')
->click('@composer-schedule-top');
- waitForComposerQueueTestId($page, 'composer-submit');
+ waitForOpen($page, '@post-composer-dialog');
+ waitFor($page, '@composer-submit');
expect($page->script('document.querySelector("[data-testid=composer-submit]").dataset.scheduleMode'))->toBe('top');
$page->click('@composer-submit');
- waitForComposerQueueClosed($page);
+ waitForGone($page, '@post-composer-dialog');
$created = Post::query()->where('workspace_id', $workspace->id)->whereKeyNot($existing->id)->sole();
@@ -329,7 +276,8 @@ test('editing a queued post to a custom time switches its marker to custom', fun
$this->actingAs($user);
$page = visit(route('app.posts.edit', $queued));
- waitForComposerQueueTestId($page, 'composer-submit');
+ waitForOpen($page, '@post-composer-dialog');
+ waitFor($page, '@composer-submit');
expect($page->script('document.querySelector("[data-testid=composer-submit]").dataset.scheduleMode'))->toBe('next');
$page->click('@composer-schedule-trigger')
@@ -341,9 +289,7 @@ test('editing a queued post to a custom time switches its marker to custom', fun
$page->click('@composer-submit');
- for ($attempt = 0; $attempt < 50 && $queued->refresh()->schedule_mode !== ScheduleMode::Custom; $attempt++) {
- $page->script('new Promise((resolve) => setTimeout(resolve, 100))');
- }
+ waitForDatabase($page, fn (): bool => $queued->refresh()->schedule_mode === ScheduleMode::Custom);
expect($queued->refresh()->schedule_mode)->toBe(ScheduleMode::Custom);
@@ -362,15 +308,17 @@ test('recovering an empty-target draft into the queue confirms it with a toast',
$this->actingAs($user);
$page = visit(route('app.posts.edit', $legacy));
- waitForComposerQueueTestId($page, 'composer-add-account');
+ waitForOpen($page, '@post-composer-dialog');
+ waitFor($page, '@composer-add-account');
$page->click('@composer-add-account')
->click("@composer-account-option-{$channel->id}");
- waitForComposerQueueTestId($page, 'composer-submit');
+ waitForOpen($page, '@post-composer-dialog');
+ waitFor($page, '@composer-submit');
expect($page->script('document.querySelector("[data-testid=composer-submit]").dataset.scheduleMode'))->toBe('next');
$page->click('@composer-submit');
- waitForComposerQueueClosed($page);
- waitForComposerQueuePageTestId($page, 'queue-added-toast');
+ waitForGone($page, '@post-composer-dialog');
+ waitFor($page, '@queue-added-toast');
$recovered = Post::query()->where('workspace_id', $workspace->id)->sole();
@@ -387,11 +335,12 @@ test('recovering an empty-target draft into the queue confirms it with a toast',
*/
function composerScheduleOpenPicker(mixed $page): void
{
- waitForComposerQueueTestId($page, 'composer-schedule-trigger');
+ waitForOpen($page, '@post-composer-dialog');
+ waitFor($page, '@composer-schedule-trigger');
$page->click('@composer-schedule-trigger');
- waitForComposerQueuePageTestId($page, 'composer-schedule-custom');
+ waitFor($page, '@composer-schedule-custom');
$page->click('@composer-schedule-custom');
- waitForComposerQueuePageTestId($page, 'composer-schedule-picker');
+ waitFor($page, '@composer-schedule-picker');
}
/**
diff --git a/tests/Browser/ComposerSharedDataTest.php b/tests/Browser/ComposerSharedDataTest.php
index 2450a48d2..525f45e96 100644
--- a/tests/Browser/ComposerSharedDataTest.php
+++ b/tests/Browser/ComposerSharedDataTest.php
@@ -66,46 +66,17 @@ function composerSharedDataPost(Workspace $workspace, SocialAccount $account, Co
]);
}
-function waitForComposerSharedDataCondition(mixed $page, string $condition): void
-{
- $page->script(<<<JS
- (async () => {
- for (let attempt = 0; attempt < 300; attempt++) {
- if ({$condition}) return;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })();
- JS);
-}
-
-function waitForComposerSharedDataTestId(mixed $page, string $testId): void
-{
- waitForComposerSharedDataCondition($page, "document.querySelector('[data-testid=\"{$testId}\"]')?.getBoundingClientRect().height > 0");
-}
-
-function waitForComposerSharedDataReady(mixed $page, string $testId): void
-{
- waitForComposerSharedDataCondition($page, <<<JS
- (() => {
- const sheet = document.querySelector('[data-testid="post-composer-dialog"]');
- return sheet?.getAttribute('data-state') === 'open'
- && sheet.getAnimations().every((animation) => animation.playState !== 'running')
- && document.querySelector('[data-testid="{$testId}"]')?.getBoundingClientRect().height > 0;
- })()
- JS);
-}
-
test('editing from the calendar opens the post with its board', function () {
[$user, $workspace, $pinterest] = composerSharedDataSetup();
$post = composerSharedDataPost($workspace, $pinterest, ContentType::PinterestPin, ['board_id' => 'board_live']);
$this->actingAs($user);
$page = visit(route('app.calendar', ['view' => 'month', 'month' => $post->scheduled_at->format('Y-m-d')]));
- waitForComposerSharedDataTestId($page, "calendar-post-{$post->id}");
+ waitFor($page, "@calendar-post-{$post->id}");
$page->click("@calendar-post-{$post->id}");
- waitForComposerSharedDataTestId($page, "post-details-edit-{$post->id}");
+ waitFor($page, "@post-details-edit-{$post->id}");
$page->click("@post-details-edit-{$post->id}");
- waitForComposerSharedDataTestId($page, 'pinterest-board-selected');
+ waitFor($page, '@pinterest-board-selected');
$page->assertSeeIn('@pinterest-board-selected', 'Live board')
->assertNoJavaScriptErrors();
@@ -117,7 +88,7 @@ function clickComposerSharedDataNewPost(mixed $page): void
for ($attempt = 0; $attempt < 3 && ! $page->script($menuOpen); $attempt++) {
$page->click('@sidebar-new');
- waitForCondition($page, $menuOpen);
+ waitForState($page, '@sidebar-new-menu[data-state="open"]', 'true');
}
waitFor($page, '@sidebar-new-post');
@@ -127,29 +98,30 @@ function clickComposerSharedDataNewPost(mixed $page): void
function openComposerFromSidebar(mixed $page): void
{
clickComposerSharedDataNewPost($page);
- waitForComposerSharedDataReady($page, 'composer-add-account');
+ waitForOpen($page, '@post-composer-dialog');
+ waitFor($page, '@composer-add-account');
}
function closeComposerSharedData(mixed $page): void
{
$page->click('@composer-close');
- waitForComposerSharedDataCondition($page, "!document.querySelector('[data-testid=\"post-composer-dialog\"]')");
+ waitForGone($page, '@post-composer-dialog');
}
function composerSharedDataZoneLabel(mixed $page, SocialAccount $channel): string
{
$page->click('@composer-add-account');
- waitForComposerSharedDataTestId($page, "composer-account-option-{$channel->id}");
+ waitFor($page, "@composer-account-option-{$channel->id}");
$page->click("@composer-account-option-{$channel->id}");
- waitForComposerSharedDataTestId($page, 'composer-schedule-trigger');
+ waitFor($page, '@composer-schedule-trigger');
$page->click('@composer-schedule-trigger');
- waitForComposerSharedDataCondition($page, "document.querySelector('[data-testid=\"composer-schedule-picker\"]') || document.querySelector('[data-testid=\"composer-schedule-custom\"]')");
+ waitForState($page, '@composer-schedule-picker, @composer-schedule-custom', 'true');
if (! $page->script('Boolean(document.querySelector(\'[data-testid="composer-schedule-picker"]\'))')) {
$page->click('@composer-schedule-custom');
}
- waitForComposerSharedDataTestId($page, 'composer-schedule-timezone');
+ waitFor($page, '@composer-schedule-timezone');
return trim((string) $page->script('document.querySelector("[data-testid=composer-schedule-timezone]").textContent'));
}
@@ -167,11 +139,12 @@ test('the next composer open shows a channel time zone the user just changed wit
$channel->update(['timezone' => 'Asia/Tokyo']);
clickComposerSharedDataNewPost($page);
- waitForComposerSharedDataTestId($page, 'composer-resume-discard');
+ waitFor($page, '@composer-resume-discard');
$page->click('@composer-resume-discard');
- waitForComposerSharedDataReady($page, 'composer-add-account');
+ waitForOpen($page, '@post-composer-dialog');
+ waitFor($page, '@composer-add-account');
composerSharedDataZoneLabel($page, $channel);
- waitForComposerSharedDataCondition($page, "document.querySelector('[data-testid=\"composer-schedule-timezone\"]')?.textContent.includes('Tokyo')");
+ waitForText($page, '@composer-schedule-timezone', 'Tokyo');
expect(trim((string) $page->script('document.querySelector("[data-testid=composer-schedule-timezone]").textContent')))->toContain('Tokyo');
$page->assertNoJavaScriptErrors();
@@ -193,7 +166,7 @@ test('a signature created in the composer is there when the composer opens again
openComposerFromSidebar($page);
$page->click('@composer-base-signature');
- waitForComposerSharedDataCondition($page, "document.querySelector('[data-testid=\"composer-signatures-popover\"]')?.textContent.includes('Launch tags')");
+ waitForText($page, '@composer-signatures-popover', 'Launch tags');
$page->assertSeeIn('@composer-signatures-popover', 'Launch tags')
->assertNoJavaScriptErrors();
@@ -221,9 +194,9 @@ test('editing a tiktok post keeps its stored interaction flags', function () {
$this->actingAs($user);
$page = visit(route('app.posts.index', ['edit' => $post->id]));
- waitForComposerSharedDataTestId($page, 'tiktok-allow-comments');
+ waitFor($page, '@tiktok-allow-comments');
$page->click('@composer-save-draft');
- waitForComposerSharedDataCondition($page, "!document.querySelector('[data-testid=\"post-composer-dialog\"]')");
+ waitForGone($page, '@post-composer-dialog');
expect(data_get($post->fresh()->meta, 'allow_comments'))->toBeTrue();
});
@@ -253,11 +226,11 @@ test('editing a post shows a server media error on the item it belongs to', func
$this->actingAs($user);
$page = visit(route('app.posts.index', ['edit' => $post->id]));
- waitForComposerSharedDataCondition($page, "document.querySelectorAll('[data-testid\$=\"-media-item\"]').length === 2");
+ waitForCount($page, '[data-testid$="-media-item"]', 2);
$media->last()->delete();
$page->click('@composer-save-draft');
- waitForComposerSharedDataCondition($page, "document.querySelector('[data-testid\$=\"-media-error-1\"]') !== null");
+ waitForState($page, '[data-testid$="-media-error-1"]', 'true');
expect($page->script("document.querySelector('[data-testid\$=\"-media-error-0\"]')"))->toBeNull();
$page->assertNoJavaScriptErrors();
diff --git a/tests/Browser/ComposerSingleChannelTest.php b/tests/Browser/ComposerSingleChannelTest.php
index 59c00aece..4114ad9d3 100644
--- a/tests/Browser/ComposerSingleChannelTest.php
+++ b/tests/Browser/ComposerSingleChannelTest.php
@@ -28,37 +28,6 @@ function singleChannelComposerWorkspace(): array
return [$user, $workspace];
}
-/**
- * The composer opens as an animated dialog and swaps editors when the channel
- * count changes. Poll from the page (never sleep()) until the element is laid out.
- */
-function waitForSingleChannelComposerTestId(mixed $page, string $testId): void
-{
- $page->script(<<<JS
- (async () => {
- for (let attempt = 0; attempt < 100; attempt++) {
- const sheet = document.querySelector('[data-testid="post-composer-dialog"]');
- if (sheet?.getAttribute('data-state') === 'open'
- && sheet.getAnimations().every((animation) => animation.playState !== 'running')
- && document.querySelector('[data-testid="{$testId}"]')?.getBoundingClientRect().height > 0) return;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })();
- JS);
-}
-
-function waitForSingleChannelComposerClosed(mixed $page): void
-{
- $page->script(<<<'JS'
- (async () => {
- for (let attempt = 0; attempt < 80; attempt++) {
- if (!document.querySelector('[data-testid="post-composer-dialog"]')) return;
- await new Promise((resolve) => setTimeout(resolve, 100));
- }
- })();
- JS);
-}
-
test('one channel opens its own editor directly and a second channel returns to the shared step', function () {
[$user, $workspace] = singleChannelComposerWorkspace();
$youtube = SocialAccount::factory()->youtube()->create(['workspace_id' => $workspace->id]);
@@ -66,7 +35,8 @@ test('one channel opens its own editor directly and a second channel returns to
$this->actingAs($user);
$page = visit(route('app.posts.create'));
- waitForSingleChannelComposerTestId($page, 'composer-add-account');
+ waitForOpen($page, '@post-composer-dialog');
+ waitFor($page, '@composer-add-account');
$page->fill('@composer-base-content', 'Typed before choosing')
->click('@composer-add-account')
->click("@composer-account-option-{$youtube->id}")
@@ -113,13 +83,14 @@ test('saving a single channel draft keeps its network fields on the post', funct
$this->actingAs($user);
$page = visit(route('app.posts.create'));
- waitForSingleChannelComposerTestId($page, 'composer-add-account');
+ waitForOpen($page, '@post-composer-dialog');
+ waitFor($page, '@composer-add-account');
$page->click('@composer-add-account')
->click("@composer-account-option-{$youtube->id}")
->fill("@composer-caption-{$youtube->id}", 'A short about the launch')
->fill('@youtube-title', 'Launch title')
->click('@composer-save-draft');
- waitForSingleChannelComposerClosed($page);
+ waitForGone($page, '@post-composer-dialog');
$post = Post::where('workspace_id', $workspace->id)->sole();
expect($post->status)->toBe(PostStatus::Draft)
@@ -135,7 +106,8 @@ test('the youtube title follows the caption until the title is edited', function
$this->actingAs($user);
$page = visit(route('app.posts.create'));
- waitForSingleChannelComposerTestId($page, 'composer-add-account');
+ waitForOpen($page, '@post-composer-dialog');
+ waitFor($page, '@composer-add-account');
$page->fill('@composer-base-content', "Typed first\nMore details below")
->click('@composer-add-account')
->click("@composer-account-option-{$youtube->id}")
@@ -153,7 +125,7 @@ test('the youtube title follows the caption until the title is edited', function
->assertValue('@youtube-title', 'My own title')
->assertNoJavaScriptErrors()
->click('@composer-save-draft');
- waitForSingleChannelComposerClosed($page);
+ waitForGone($page, '@post-composer-dialog');
$post = Post::where('workspace_id', $workspace->id)->sole();
expect(data_get($post->meta, 'title'))->toBe('My own title');
@@ -165,14 +137,16 @@ test('scheduling a single channel saves its post with the chosen format', functi
$this->actingAs($user);
$page = visit(route('app.posts.create'));
- waitForSingleChannelComposerTestId($page, 'composer-add-account');
+ waitForOpen($page, '@post-composer-dialog');
+ waitFor($page, '@composer-add-account');
$page->click('@composer-add-account')
->click("@composer-account-option-{$facebook->id}")
->assertVisible("@composer-type-{$facebook->id}")
->fill("@composer-caption-{$facebook->id}", 'Scheduled for one page')
->click('@composer-schedule-trigger')
->click('@composer-schedule-custom');
- waitForSingleChannelComposerTestId($page, 'composer-schedule-picker');
+ waitForOpen($page, '@post-composer-dialog');
+ waitFor($page, '@composer-schedule-picker');
$query = '[...document.querySelectorAll("[data-testid^=composer-schedule-day-]")].find((day) => !day.hasAttribute("data-disabled") && !day.hasAttribute("data-outside-view") && !day.hasAttribute("data-zone-today"))?.dataset.testid.replace("composer-schedule-day-", "") ?? null';
$day = $page->script($query);
@@ -184,7 +158,7 @@ test('scheduling a single channel saves its post with the chosen format', functi
->fill('@composer-schedule-time-input', '1715')
->click('@composer-schedule-done')
->click('@composer-submit');
- waitForSingleChannelComposerClosed($page);
+ waitForGone($page, '@post-composer-dialog');
$post = Post::where('workspace_id', $workspace->id)->sole();
expect($post->status)->toBe(PostStatus::Scheduled)
@@ -207,7 +181,8 @@ test('editing a single channel post opens its own editor', function () {
$this->actingAs($user);
$page = visit(route('app.posts.edit', $post));
- waitForSingleChannelComposerTestId($page, 'composer-customization');
+ waitForOpen($page, '@post-composer-dialog');
+ waitFor($page, '@composer-customization');
$page->assertValue("@composer-caption-{$account->id}", 'Already written')
->assertVisible('@composer-submit')
->assertMissing('@composer-next')
@@ -223,7 +198,8 @@ test('a channel that needs media keeps the shared step and shows the requirement
$this->actingAs($user);
$page = visit(route('app.posts.create'));
- waitForSingleChannelComposerTestId($page, 'composer-add-account');
+ waitForOpen($page, '@post-composer-dialog');
+ waitFor($page, '@composer-add-account');
$page->click('@composer-add-account')
->click("@composer-account-option-{$x->id}")
->fill("@composer-caption-{$x->id}", 'Text only')
diff --git a/tests/Browser/ComposerTemplatesTest.php b/tests/Browser/ComposerTemplatesTest.php
index a8c4cb443..49e881480 100644
--- a/tests/Browser/ComposerTemplatesTest.php
+++ b/tests/Browser/ComposerTemplatesTest.php
@@ -9,61 +9,6 @@ use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
-function waitForComposerTemplatesTestId(mixed $page, string $testId): void
-{
- $page->script(<<<JS
- (async () => {
- for (let attempt = 0; attempt < 200; attempt++) {
- if (document.querySelector('[data-testid="{$testId}"]')?.getBoundingClientRect().height > 0) return;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })();
- JS);
-}
-
-function waitForComposerTemplatesCondition(mixed $page, string $condition): void
-{
- $page->script(<<<JS
- (async () => {
- for (let attempt = 0; attempt < 200; attempt++) {
- if ({$condition}) return;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })();
- JS);
-}
-
-/**
- * Dialogs animate in; a click that lands before the animation settles is swallowed.
- */
-function waitForComposerTemplatesDialog(mixed $page, string $testId): void
-{
- $page->script(<<<JS
- (async () => {
- for (let attempt = 0; attempt < 200; attempt++) {
- const dialog = document.querySelector('[data-testid="{$testId}"]');
- if (dialog?.getAttribute('data-state') === 'open'
- && dialog.getAnimations().every((animation) => animation.playState !== 'running')) return;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })();
- JS);
-}
-
-function waitForComposerTemplatesDatabase(mixed $page, Closure $condition): void
-{
- for ($attempt = 0; $attempt < 50 && ! $condition(); $attempt++) {
- $page->script('new Promise((resolve) => setTimeout(resolve, 100))');
- }
-}
-
-function composerTemplatesListHas(string $text): string
-{
- $expected = json_encode($text);
-
- return "(document.querySelector('[data-testid=\"composer-templates-list\"]')?.textContent ?? '').includes({$expected})";
-}
-
/**
* @return array{0: User, 1: Workspace}
*/
@@ -86,15 +31,15 @@ function openComposerTemplates(User $user, string $content = ''): mixed
test()->actingAs($user);
$page = visit(route('app.posts.create'));
- waitForComposerTemplatesDialog($page, 'post-composer-dialog');
- waitForComposerTemplatesTestId($page, 'composer-base-content');
+ waitForOpen($page, '@post-composer-dialog');
+ waitFor($page, '@composer-base-content');
if ($content !== '') {
$page->fill('@composer-base-content', $content);
}
$page->click('@composer-templates-toggle');
- waitForComposerTemplatesTestId($page, 'composer-template-quick_win');
+ waitFor($page, '@composer-template-quick_win');
return $page;
}
@@ -133,24 +78,24 @@ test('in the per-network view a template goes to the expanded account override o
$this->actingAs($user);
$page = visit(route('app.posts.create'));
- waitForComposerTemplatesDialog($page, 'post-composer-dialog');
- waitForComposerTemplatesTestId($page, 'composer-add-account');
+ waitForOpen($page, '@post-composer-dialog');
+ waitFor($page, '@composer-add-account');
$page->fill('@composer-base-content', 'Hello world')
->click('@composer-add-account')
->click("@composer-account-option-{$linkedIn->id}")
->click("@composer-account-option-{$x->id}")
->click('@composer-next');
- waitForComposerTemplatesTestId($page, 'composer-customization');
+ waitFor($page, '@composer-customization');
$page->click("@composer-account-{$linkedIn->id}");
- waitForComposerTemplatesTestId($page, "composer-caption-{$linkedIn->id}");
+ waitFor($page, "@composer-caption-{$linkedIn->id}");
$page->click('@composer-templates-toggle')
->click('@composer-templates-tab-team');
- waitForComposerTemplatesTestId($page, "composer-template-{$template->id}");
+ waitFor($page, "@composer-template-{$template->id}");
$page->click("@composer-template-{$template->id}");
$page->assertValue("@composer-caption-{$linkedIn->id}", "Hello world\n\nTeam body")
->click("@composer-account-{$x->id}");
- waitForComposerTemplatesTestId($page, "composer-caption-{$x->id}");
+ waitFor($page, "@composer-caption-{$x->id}");
$page->assertValue("@composer-caption-{$x->id}", 'Hello world')
->assertNoJavaScriptErrors();
@@ -166,13 +111,13 @@ test('the personal tab lists only the actor templates with their badge and searc
$page = openComposerTemplates($user);
$page->click('@composer-templates-tab-personal');
- waitForComposerTemplatesTestId($page, "composer-template-{$mine->id}");
+ waitFor($page, "@composer-template-{$mine->id}");
$page->assertVisible("@composer-template-{$other->id}")
->assertMissing("@composer-template-{$theirs->id}")
->assertSeeIn("@composer-template-visibility-{$mine->id}", __('create.templates.visibility.personal'))
->fill('@composer-templates-search', 'Monday');
- waitForComposerTemplatesCondition($page, "!document.querySelector('[data-testid=\"composer-template-{$other->id}\"]')");
+ waitForGone($page, "@composer-template-{$other->id}");
$page->assertVisible("@composer-template-{$mine->id}")
->assertMissing("@composer-template-{$other->id}")
@@ -209,14 +154,14 @@ test('the new template button creates a team template without touching the draft
$page = openComposerTemplates($user, 'Hello');
$page->click('@composer-templates-tab-team')
->click('@composer-templates-new');
- waitForComposerTemplatesDialog($page, 'template-editor');
+ waitForOpen($page, '@template-editor');
$page->assertValue('@template-editor-body', '')
->assertSeeIn('@template-editor-visibility', __('create.templates.visibility.team'))
->fill('@template-editor-title', 'Launch checklist')
->fill('@template-editor-body', "• Date\n• Owner")
->click('@template-editor-save');
- waitForComposerTemplatesCondition($page, composerTemplatesListHas('Launch checklist'));
+ waitForText($page, '@composer-templates-list', 'Launch checklist');
$template = PostTemplate::query()->where('workspace_id', $workspace->id)->sole();
@@ -240,31 +185,31 @@ test('edit, duplicate and delete from the panel never touch the draft', function
$page = openComposerTemplates($user, 'Hello');
$page->click('@composer-templates-tab-personal');
- waitForComposerTemplatesTestId($page, "composer-template-{$template->id}");
+ waitFor($page, "@composer-template-{$template->id}");
$page->click("@composer-template-menu-{$template->id}");
- waitForComposerTemplatesTestId($page, "template-edit-{$template->id}");
+ waitFor($page, "@template-edit-{$template->id}");
$page->click("@template-edit-{$template->id}");
- waitForComposerTemplatesDialog($page, 'template-editor');
+ waitForOpen($page, '@template-editor');
$page->assertValue('@template-editor-title', 'Old title')
->fill('@template-editor-title', 'New title')
->click('@template-editor-save');
- waitForComposerTemplatesCondition($page, composerTemplatesListHas('New title'));
+ waitForText($page, '@composer-templates-list', 'New title');
expect($template->fresh()->title)->toBe('New title');
$page->assertMissing('@template-editor')
->assertValue('@composer-base-content', 'Hello');
$page->click("@composer-template-menu-{$template->id}");
- waitForComposerTemplatesTestId($page, "template-duplicate-{$template->id}");
+ waitFor($page, "@template-duplicate-{$template->id}");
$page->click("@template-duplicate-{$template->id}");
- waitForComposerTemplatesDialog($page, 'template-duplicate-dialog');
+ waitForOpen($page, '@template-duplicate-dialog');
$page->assertSeeIn('@template-duplicate-dialog', 'New title')
->click('@template-duplicate-visibility');
- waitForComposerTemplatesTestId($page, 'template-duplicate-visibility-team');
+ waitFor($page, '@template-duplicate-visibility-team');
$page->click('@template-duplicate-visibility-team')
->click('@template-duplicate-confirm');
- waitForComposerTemplatesCondition($page, composerTemplatesListHas('New title (copy)'));
+ waitForText($page, '@composer-templates-list', 'New title (copy)');
$copy = PostTemplate::query()->where('workspace_id', $workspace->id)->whereKeyNot($template->id)->sole();
@@ -275,13 +220,13 @@ test('edit, duplicate and delete from the panel never touch the draft', function
->assertValue('@composer-base-content', 'Hello');
$page->click("@composer-template-menu-{$copy->id}");
- waitForComposerTemplatesTestId($page, "template-delete-{$copy->id}");
+ waitFor($page, "@template-delete-{$copy->id}");
$page->click("@template-delete-{$copy->id}");
- waitForComposerTemplatesDialog($page, 'confirm-delete-modal');
+ waitForOpen($page, '@confirm-delete-modal');
$page->assertMissing('@confirm-delete-input')
->click('@template-delete-confirm');
- waitForComposerTemplatesDatabase($page, fn () => PostTemplate::query()->whereKey($copy->id)->doesntExist());
- waitForComposerTemplatesCondition($page, "!document.querySelector('[data-testid=\"composer-template-{$copy->id}\"]')");
+ waitForDatabase($page, fn () => PostTemplate::query()->whereKey($copy->id)->doesntExist());
+ waitForGone($page, "@composer-template-{$copy->id}");
expect(PostTemplate::query()->whereKey($copy->id)->exists())->toBeFalse()
->and(PostTemplate::query()->whereKey($template->id)->exists())->toBeTrue();
@@ -296,8 +241,8 @@ test('at 390px the header fits and every side panel toggle works', function () {
$this->actingAs($user);
$page = visit(route('app.posts.create'))->resize(390, 844);
- waitForComposerTemplatesDialog($page, 'post-composer-dialog');
- waitForComposerTemplatesTestId($page, 'composer-templates-toggle');
+ waitForOpen($page, '@post-composer-dialog');
+ waitFor($page, '@composer-templates-toggle');
$overflow = $page->script(<<<'JS'
(() => {
@@ -313,17 +258,17 @@ test('at 390px the header fits and every side panel toggle works', function () {
expect($overflow)->toBeFalse();
$page->click('@composer-templates-toggle');
- waitForComposerTemplatesDialog($page, 'composer-templates-sheet');
+ waitForOpen($page, '@composer-templates-sheet');
$page->assertVisible('@composer-templates-panel')
->click('@composer-templates-sheet-close');
- waitForComposerTemplatesCondition($page, "!document.querySelector('[data-testid=\"composer-templates-sheet\"]')");
+ waitForGone($page, '@composer-templates-sheet');
$page->click('@composer-ai-assistant');
- waitForComposerTemplatesDialog($page, 'composer-assistant-sheet');
+ waitForOpen($page, '@composer-assistant-sheet');
$page->assertVisible('@composer-assistant-panel')
->click('@composer-assistant-sheet-close');
- waitForComposerTemplatesCondition($page, "!document.querySelector('[data-testid=\"composer-assistant-sheet\"]')");
+ waitForGone($page, '@composer-assistant-sheet');
$page->click('@composer-view-preview');
- waitForComposerTemplatesTestId($page, 'composer-previews-scroll');
+ waitFor($page, '@composer-previews-scroll');
$page->assertVisible('@composer-previews-scroll')
->assertAttribute('@composer-view-preview', 'aria-pressed', 'true')
@@ -335,8 +280,8 @@ test('a failed template load shows an inline error and retry recovers', function
$this->actingAs($user);
$page = visit(route('app.posts.create'));
- waitForComposerTemplatesDialog($page, 'post-composer-dialog');
- waitForComposerTemplatesTestId($page, 'composer-templates-toggle');
+ waitForOpen($page, '@post-composer-dialog');
+ waitFor($page, '@composer-templates-toggle');
$page->script(<<<'JS'
(() => {
const open = XMLHttpRequest.prototype.open;
@@ -348,12 +293,12 @@ test('a failed template load shows an inline error and retry recovers', function
})()
JS);
$page->click('@composer-templates-toggle');
- waitForComposerTemplatesTestId($page, 'composer-templates-error');
+ waitFor($page, '@composer-templates-error');
$page->assertVisible('@composer-templates-retry');
$page->script('window.__restoreXhr()');
$page->click('@composer-templates-retry');
- waitForComposerTemplatesTestId($page, 'composer-template-quick_win');
+ waitFor($page, '@composer-template-quick_win');
$page->assertMissing('@composer-templates-error')->assertNoJavaScriptErrors();
});
diff --git a/tests/Browser/ComposerTimezoneTest.php b/tests/Browser/ComposerTimezoneTest.php
index f258f79ba..b715d1391 100644
--- a/tests/Browser/ComposerTimezoneTest.php
+++ b/tests/Browser/ComposerTimezoneTest.php
@@ -12,40 +12,9 @@ use App\Models\Workspace;
use App\Support\PostingSchedule;
use Carbon\CarbonImmutable;
-function waitForComposerTimezoneTestId(mixed $page, string $testId): void
-{
- $page->script(<<<JS
- (async () => {
- for (let attempt = 0; attempt < 100; attempt++) {
- if (document.querySelector('[data-testid="{$testId}"]')?.getBoundingClientRect().height > 0) return;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })();
- JS);
-}
-
-function waitForComposerTimezoneClosed(mixed $page): void
-{
- $page->script(<<<'JS'
- (async () => {
- for (let attempt = 0; attempt < 100; attempt++) {
- if (!document.querySelector('[data-testid="post-composer-dialog"]')) return;
- await new Promise((resolve) => setTimeout(resolve, 100));
- }
- })();
- JS);
-}
-
function waitForComposerTimezoneTrigger(mixed $page, string $label): void
{
- $page->script(<<<JS
- (async () => {
- for (let attempt = 0; attempt < 100; attempt++) {
- if (document.querySelector('[data-testid="composer-schedule-trigger"]')?.textContent.trim() === '{$label}') return;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })();
- JS);
+ waitForState($page, '@composer-schedule-trigger', "element.textContent.trim() === '{$label}'");
}
/**
@@ -73,11 +42,11 @@ function composerTimezoneChannel(Workspace $workspace, string $timezone, ?Postin
function composerTimezoneSelect(mixed $page, SocialAccount ...$channels): void
{
- waitForComposerTimezoneTestId($page, 'composer-add-account');
+ waitFor($page, '@composer-add-account');
$page->click('@composer-add-account');
foreach ($channels as $channel) {
- waitForComposerTimezoneTestId($page, "composer-account-option-{$channel->id}");
+ waitFor($page, "@composer-account-option-{$channel->id}");
$page->click("@composer-account-option-{$channel->id}");
}
}
@@ -88,22 +57,15 @@ function composerTimezoneSelect(mixed $page, SocialAccount ...$channels): void
*/
function composerTimezoneOpenPicker(mixed $page): void
{
- waitForComposerTimezoneTestId($page, 'composer-schedule-trigger');
+ waitFor($page, '@composer-schedule-trigger');
$page->click('@composer-schedule-trigger');
- $page->script(<<<'JS'
- (async () => {
- for (let attempt = 0; attempt < 100; attempt++) {
- if (document.querySelector('[data-testid="composer-schedule-picker"]') || document.querySelector('[data-testid="composer-schedule-custom"]')) return;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })();
- JS);
+ waitForState($page, '@composer-schedule-picker, @composer-schedule-custom', 'true');
if (! $page->script('Boolean(document.querySelector(\'[data-testid="composer-schedule-picker"]\'))')) {
$page->click('@composer-schedule-custom');
}
- waitForComposerTimezoneTestId($page, 'composer-schedule-picker');
+ waitFor($page, '@composer-schedule-picker');
}
function composerTimezonePickFutureDay(mixed $page): string
@@ -155,7 +117,7 @@ test('one channel shows and takes times in its own zone', function () {
expect(composerTimezoneTrigger($page))->toBe(composerTimezoneLabel($instant));
$page->click('@composer-submit');
- waitForComposerTimezoneClosed($page);
+ waitForGone($page, '@post-composer-dialog');
expect(Post::query()->where('workspace_id', $workspace->id)->sole()->scheduled_at->toIso8601String())
->toBe($instant->utc()->toIso8601String());
@@ -185,7 +147,7 @@ test('changing the channels keeps the picked instant and shows it in the new zon
expect(composerTimezoneTrigger($page))->toBe(composerTimezoneLabel($instant));
$page->click('@composer-submit');
- waitForComposerTimezoneClosed($page);
+ waitForGone($page, '@post-composer-dialog');
expect(Post::query()->where('workspace_id', $workspace->id)->sole()->scheduled_at->toIso8601String())
->toBe($instant->utc()->toIso8601String());
@@ -220,7 +182,7 @@ test('editing a scheduled post shows its time in the channel zone', function ()
->and($page->script('document.querySelector("[data-testid=composer-schedule-time-input]").value'))->toBe('10:00');
$page->click('@composer-schedule-done')->click('@composer-submit');
- waitForComposerTimezoneClosed($page);
+ waitForGone($page, '@post-composer-dialog');
expect($post->fresh()->scheduled_at->toIso8601String())->toBe($instant->utc()->toIso8601String());
$page->assertNoJavaScriptErrors();
@@ -275,7 +237,7 @@ test('one channel offers its posting slots for the picked day', function () {
$weekday = CarbonImmutable::parse($day)->dayOfWeek;
$evening = composerTimezoneEveningSlot($weekday);
$testId = fn (string $time): string => 'composer-schedule-slot-'.str_replace(':', '', $time);
- waitForComposerTimezoneTestId($page, $testId($evening));
+ waitFor($page, '@'.$testId($evening));
$page->assertVisible('@'.$testId(composerTimezoneMorningSlot($weekday)))
->assertMissing('@'.$testId(composerTimezoneEveningSlot(($weekday + 1) % 7)))
@@ -287,7 +249,7 @@ test('one channel offers its posting slots for the picked day', function () {
expect(composerTimezoneTrigger($page))->toBe(composerTimezoneLabel($instant));
$page->click('@composer-submit');
- waitForComposerTimezoneClosed($page);
+ waitForGone($page, '@post-composer-dialog');
expect(Post::query()->where('workspace_id', $workspace->id)->sole()->scheduled_at->toIso8601String())
->toBe($instant->utc()->toIso8601String());
@@ -309,15 +271,8 @@ test('posting slots already taken by a scheduled post are disabled', function ()
$page = visit(route('app.posts.create'));
composerTimezoneSelect($page, $channel);
composerTimezoneOpenPicker($page);
- waitForComposerTimezoneTestId($page, 'composer-schedule-slot-1600');
- $page->script(<<<'JS'
- (async () => {
- for (let attempt = 0; attempt < 80; attempt++) {
- if (document.querySelector('[data-testid="composer-schedule-slot-1500"]')?.disabled) return;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })();
- JS);
+ waitFor($page, '@composer-schedule-slot-1600');
+ waitForState($page, '@composer-schedule-slot-1500', 'element.disabled');
expect($page->script('document.querySelector("[data-testid=composer-schedule-slot-1500]").disabled'))->toBeTrue()
->and($page->script('document.querySelector("[data-testid=composer-schedule-slot-1600]").disabled'))->toBeFalse();
@@ -350,16 +305,16 @@ test('a calendar hour opens the composer at the same moment, shown in the channe
$this->actingAs($user);
$page = visit(route('app.channels.calendar', ['account' => $warsaw->id, 'view' => 'week', 'week' => $day, 'tz' => 'America/Sao_Paulo']));
- waitForComposerTimezoneTestId($page, "calendar-add-{$day}-10");
+ waitFor($page, "@calendar-add-{$day}-10");
$page->click("@calendar-add-{$day}-10");
- waitForComposerTimezoneTestId($page, "composer-caption-{$warsaw->id}");
+ waitFor($page, "@composer-caption-{$warsaw->id}");
$instant = CarbonImmutable::parse("{$day} 10:00", 'America/Sao_Paulo');
waitForComposerTimezoneTrigger($page, composerTimezoneLabel($instant->setTimezone('Europe/Warsaw')));
expect(composerTimezoneTrigger($page))->toBe(composerTimezoneLabel($instant->setTimezone('Europe/Warsaw')));
$page->fill("@composer-caption-{$warsaw->id}", 'From the calendar')->click('@composer-submit');
- waitForComposerTimezoneClosed($page);
+ waitForGone($page, '@post-composer-dialog');
expect(Post::query()->where('workspace_id', $workspace->id)->sole()->scheduled_at->toIso8601String())
->toBe($instant->utc()->toIso8601String());
diff --git a/tests/Browser/ComposerXPollTest.php b/tests/Browser/ComposerXPollTest.php
index 2f6641151..1c0c051ed 100644
--- a/tests/Browser/ComposerXPollTest.php
+++ b/tests/Browser/ComposerXPollTest.php
@@ -388,7 +388,7 @@ function openCustomizedXPollComposer(Post $post): array
$linkedIn = SocialAccount::factory()->linkedin()->create(['workspace_id' => $post->workspace_id]);
$page = visit(route('app.posts.create'))->resize(1280, 900);
- waitForState($page, '@post-composer-dialog', "element.getAttribute('data-state') === 'open' && element.getAnimations().every((animation) => animation.playState !== 'running')");
+ waitForOpen($page, '@post-composer-dialog');
$page->click('@composer-add-account');
waitFor($page, "@composer-account-option-{$linkedIn->id}");
$page->click("@composer-account-option-{$linkedIn->id}");
@@ -437,7 +437,7 @@ test('a poll picked while x was the only network turns back into a post when ano
$png = base64_encode((string) file_get_contents(base_path('tests/fixtures/crop-quadrants.png')));
$page = visit(route('app.posts.create'))->resize(1280, 900);
- waitForState($page, '@post-composer-dialog', "element.getAttribute('data-state') === 'open' && element.getAnimations().every((animation) => animation.playState !== 'running')");
+ waitForOpen($page, '@post-composer-dialog');
$page->click('@composer-add-account');
waitFor($page, "@composer-account-option-{$x->id}");
$page->click("@composer-account-option-{$x->id}")
@@ -484,7 +484,7 @@ test('a threads ghost post stays a ghost post when another network joins, since
$linkedIn = SocialAccount::factory()->linkedin()->create(['workspace_id' => $post->workspace_id]);
$page = visit(route('app.posts.create'))->resize(1280, 900);
- waitForState($page, '@post-composer-dialog', "element.getAttribute('data-state') === 'open' && element.getAnimations().every((animation) => animation.playState !== 'running')");
+ waitForOpen($page, '@post-composer-dialog');
$page->click('@composer-add-account');
waitFor($page, "@composer-account-option-{$threads->id}");
$page->click("@composer-account-option-{$threads->id}")
@@ -634,7 +634,7 @@ test('a server error on the poll shows on the x card when x is not the first cha
$linkedIn = SocialAccount::factory()->linkedin()->create(['workspace_id' => $post->workspace_id]);
$page = visit(route('app.posts.create'))->resize(1280, 900);
- waitForState($page, '@post-composer-dialog', "element.getAttribute('data-state') === 'open' && element.getAnimations().every((animation) => animation.playState !== 'running')");
+ waitForOpen($page, '@post-composer-dialog');
$page->click('@composer-add-account');
waitFor($page, "@composer-account-option-{$linkedIn->id}");
$page->click("@composer-account-option-{$linkedIn->id}");
@@ -824,7 +824,7 @@ test('a thread reply turns into a poll from its toolbar, turns its media off and
$page->fill('@thread-reply-0-poll-choice-0', 'Tabs')
->fill('@thread-reply-0-poll-choice-1', 'Spaces');
waitFor($page, "@composer-{$id}-media-source-disabled");
- waitForText($page, '@preview-thread-reply-0 [data-testid="x-preview-poll"]', 'Spaces');
+ waitForText($page, '@preview-thread-reply-0 @x-preview-poll', 'Spaces');
$page->assertMissing("@composer-{$id}-poll")
->assertMissing('@x-poll')
@@ -852,7 +852,7 @@ test('a thread reply poll shows in the preview before its question, and its choi
waitFor($page, '@thread-reply-0-poll-choice-0');
$page->fill('@thread-reply-0-poll-choice-0', 'Tabs')
->fill('@thread-reply-0-poll-choice-1', 'Tabs');
- waitForText($page, '@preview-thread-reply-0 [data-testid="x-preview-poll"]', 'Tabs');
+ waitForText($page, '@preview-thread-reply-0 @x-preview-poll', 'Tabs');
$page->assertVisible('[data-testid="preview-thread-reply-0"] [data-testid="x-preview-poll"]')
->click('@composer-save-draft');
waitForText($page, '@thread-reply-0-poll-options-error', __('posts.form.x.poll.options_distinct'));
@@ -978,7 +978,7 @@ test('every toolbar button names itself in a tooltip and the ai-generated hint o
waitForGone($page, '@thread-add-reply-tooltip');
$page->hover('@x-ai-generated-info');
- waitForState($page, '@x-ai-generated-tooltip', "element.getAttribute('data-state') === 'delayed-open' && element.getAnimations().every((animation) => animation.playState !== 'running')");
+ waitForOpen($page, '@x-ai-generated-tooltip', 'delayed-open');
expect($page->script("document.querySelector('[data-testid=\"x-ai-generated-tooltip\"]').getBoundingClientRect().bottom <= document.querySelector('[data-testid=\"x-ai-generated-info\"]').getBoundingClientRect().top"))->toBeTrue();
$page->assertNoJavaScriptErrors();
diff --git a/tests/Browser/ConnectChannelDialogTest.php b/tests/Browser/ConnectChannelDialogTest.php
index 5ebfaf65e..167d6dee1 100644
--- a/tests/Browser/ConnectChannelDialogTest.php
+++ b/tests/Browser/ConnectChannelDialogTest.php
@@ -6,20 +6,6 @@ use App\Models\User;
use App\Models\Workspace;
use Laravel\Socialite\Facades\Socialite;
-function waitForConnectDialogTestId(mixed $page, string $testId): void
-{
- $page->script(<<<JS
- (async () => {
- const sel = '[data-testid="{$testId}"]';
- for (let i = 0; i < 100; i++) {
- const el = document.querySelector(sel);
- if (el && el.getBoundingClientRect().height > 0) return;
- await new Promise((r) => setTimeout(r, 50));
- }
- })();
- JS);
-}
-
/**
* Every network's consent screen is replaced by a page of the app that says
* which driver it was, so a started connection never leaves the test.
@@ -68,9 +54,9 @@ test('the connect button opens the network grid', function () {
$this->actingAs(connectDialogAdmin());
$page = visit(route('app.workspace.channels'));
- waitForConnectDialogTestId($page, 'channels-empty-connect');
+ waitFor($page, '@channels-empty-connect');
$page->click('@channels-empty-connect');
- waitForConnectDialogTestId($page, 'connect-channel-dialog');
+ waitFor($page, '@connect-channel-dialog');
$page->assertVisible('@connect-channel-linkedin')
->assertVisible('@connect-channel-instagram')
@@ -81,17 +67,17 @@ test('instagram shows its method step inside the same dialog and can go back', f
$this->actingAs(connectDialogAdmin());
$page = visit(route('app.workspace.channels'));
- waitForConnectDialogTestId($page, 'channels-empty-connect');
+ waitFor($page, '@channels-empty-connect');
$page->click('@channels-empty-connect');
- waitForConnectDialogTestId($page, 'connect-channel-instagram');
+ waitFor($page, '@connect-channel-instagram');
$page->click('@connect-channel-instagram');
- waitForConnectDialogTestId($page, 'instagram-connect-standalone');
+ waitFor($page, '@instagram-connect-standalone');
$page->assertVisible('@instagram-connect-standalone')
->assertMissing('@connect-channel-linkedin');
$page->click('@connect-channel-back');
- waitForConnectDialogTestId($page, 'connect-channel-linkedin');
+ waitFor($page, '@connect-channel-linkedin');
$page->assertVisible('@connect-channel-linkedin')->assertNoJavaScriptErrors();
});
@@ -101,9 +87,9 @@ test('an oauth network leaves for its consent screen in the same tab', function
stubConnectDialogProviders();
$page = visit(route('app.workspace.channels'));
- waitForConnectDialogTestId($page, 'channels-empty-connect');
+ waitFor($page, '@channels-empty-connect');
$page->click('@channels-empty-connect');
- waitForConnectDialogTestId($page, 'connect-channel-linkedin');
+ waitFor($page, '@connect-channel-linkedin');
$page->click('@connect-channel-linkedin');
expect(connectDialogReachedProvider($page))->toBe('linkedin-openid');
@@ -114,9 +100,9 @@ test('the connect dialog is a fixed 840 by 700 frame with the grid scrolling ins
$this->actingAs(connectDialogAdmin());
$page = visit(route('app.workspace.channels'));
- waitForConnectDialogTestId($page, 'channels-empty-connect');
+ waitFor($page, '@channels-empty-connect');
$page->click('@channels-empty-connect');
- waitForConnectDialogTestId($page, 'channel-platform-grid');
+ waitFor($page, '@channel-platform-grid');
$frame = $page->script(<<<'JS'
(() => {
@@ -146,12 +132,12 @@ test('the info button opens the network details and back returns to the grid', f
$this->actingAs(connectDialogAdmin());
$page = visit(route('app.workspace.channels'));
- waitForConnectDialogTestId($page, 'channels-empty-connect');
+ waitFor($page, '@channels-empty-connect');
$page->click('@channels-empty-connect');
- waitForConnectDialogTestId($page, 'connect-channel-bluesky');
+ waitFor($page, '@connect-channel-bluesky');
$page->hover('@connect-channel-bluesky');
$page->click('@connect-info-bluesky');
- waitForConnectDialogTestId($page, 'connect-details');
+ waitFor($page, '@connect-details');
$page->assertVisible('@connect-details')
->assertVisible('@connect-details-help')
@@ -159,7 +145,7 @@ test('the info button opens the network details and back returns to the grid', f
->assertMissing('@channel-platform-grid');
$page->click('@connect-details-back');
- waitForConnectDialogTestId($page, 'connect-channel-bluesky');
+ waitFor($page, '@connect-channel-bluesky');
$page->assertVisible('@channel-platform-grid')
->assertMissing('@connect-details')
@@ -171,12 +157,12 @@ test('connecting from the details view starts the same flow as the card', functi
stubConnectDialogProviders();
$page = visit(route('app.workspace.channels'));
- waitForConnectDialogTestId($page, 'channels-empty-connect');
+ waitFor($page, '@channels-empty-connect');
$page->click('@channels-empty-connect');
- waitForConnectDialogTestId($page, 'connect-channel-linkedin');
+ waitFor($page, '@connect-channel-linkedin');
$page->hover('@connect-channel-linkedin');
$page->click('@connect-info-linkedin');
- waitForConnectDialogTestId($page, 'connect-details-connect');
+ waitFor($page, '@connect-details-connect');
$page->click('@connect-details-connect');
expect(connectDialogReachedProvider($page))->toBe('linkedin-openid');
@@ -187,14 +173,14 @@ test('instagram details connect opens the method step in the dialog', function (
$this->actingAs(connectDialogAdmin());
$page = visit(route('app.workspace.channels'));
- waitForConnectDialogTestId($page, 'channels-empty-connect');
+ waitFor($page, '@channels-empty-connect');
$page->click('@channels-empty-connect');
- waitForConnectDialogTestId($page, 'connect-channel-instagram');
+ waitFor($page, '@connect-channel-instagram');
$page->hover('@connect-channel-instagram');
$page->click('@connect-info-instagram');
- waitForConnectDialogTestId($page, 'connect-details-connect');
+ waitFor($page, '@connect-details-connect');
$page->click('@connect-details-connect');
- waitForConnectDialogTestId($page, 'instagram-connect-standalone');
+ waitFor($page, '@instagram-connect-standalone');
$page->assertVisible('@instagram-connect-standalone')
->assertMissing('@connect-details')
@@ -204,11 +190,11 @@ test('instagram details connect opens the method step in the dialog', function (
function openInstagramConnectStep(): mixed
{
$page = visit(route('app.workspace.channels'));
- waitForConnectDialogTestId($page, 'channels-empty-connect');
+ waitFor($page, '@channels-empty-connect');
$page->click('@channels-empty-connect');
- waitForConnectDialogTestId($page, 'connect-channel-instagram');
+ waitFor($page, '@connect-channel-instagram');
$page->click('@connect-channel-instagram');
- waitForConnectDialogTestId($page, 'instagram-connect-professional');
+ waitFor($page, '@instagram-connect-professional');
return $page;
}
@@ -251,13 +237,7 @@ test('the instagram step offers the instagram login and facebook cards side by s
$page->assertSeeIn('@instagram-connect-standalone-requirements', trans('accounts.instagram_connect.convert_hint'))
->assertVisible('@instagram-connect-facebook-requirements')
->click('@instagram-connect-facebook-requirements-toggle');
- $page->script(<<<'JS'
- (async () => {
- for (let i = 0; i < 100 && document.querySelector('[data-testid="instagram-connect-facebook-requirements"]'); i++) {
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })()
- JS);
+ waitForGone($page, '@instagram-connect-facebook-requirements');
$page->assertMissing('@instagram-connect-facebook-requirements')
->assertVisible('@instagram-connect-standalone-requirements');
@@ -268,7 +248,7 @@ test('the instagram step offers the instagram login and facebook cards side by s
->and($instagramCardText)->not->toContain('Personal');
$page->click('@instagram-connect-help');
- waitForConnectDialogTestId($page, 'instagram-connect-help-convert');
+ waitFor($page, '@instagram-connect-help-convert');
$links = $page->script(<<<'JS'
(() => ['account-type', 'convert'].map((key) => {
@@ -283,29 +263,22 @@ test('the instagram step offers the instagram login and facebook cards side by s
['host' => 'help.instagram.com', 'target' => '_blank', 'text' => trans('accounts.instagram_connect.help.convert')],
]);
$page->keys('@instagram-connect-help', 'Escape');
- $page->script(<<<'JS'
- (async () => {
- for (let i = 0; i < 100; i++) {
- if (!document.querySelector('[data-testid="instagram-connect-help-convert"]')) return;
- await new Promise((r) => setTimeout(r, 50));
- }
- })();
- JS);
+ waitForGone($page, '@instagram-connect-help-convert');
$page->click('@dialog-close');
- waitForConnectDialogTestId($page, 'connect-channel-exit-confirm');
+ waitFor($page, '@connect-channel-exit-confirm');
$page->assertSeeIn('@connect-channel-exit-confirm', trans('channels.dialog.exit_confirm.title', ['network' => 'Instagram']));
$page->click('@connect-channel-exit-continue');
- waitForConnectDialogTestId($page, 'instagram-connect-professional');
+ waitFor($page, '@instagram-connect-professional');
$page->assertMissing('@connect-channel-exit-confirm')
->assertVisible('@instagram-connect-professional')
->assertNoJavaScriptErrors();
$page->click('@dialog-close');
- waitForConnectDialogTestId($page, 'connect-channel-exit-leave');
+ waitFor($page, '@connect-channel-exit-leave');
$page->click('@connect-channel-exit-leave');
$page->assertMissing('@connect-channel-exit-confirm')
@@ -317,11 +290,11 @@ test('on a phone the instagram step stacks the facebook card under the instagram
$this->actingAs(connectDialogAdmin());
$page = visit(route('app.workspace.channels'))->resize(390, 844);
- waitForConnectDialogTestId($page, 'channels-empty-connect');
+ waitFor($page, '@channels-empty-connect');
$page->click('@channels-empty-connect');
- waitForConnectDialogTestId($page, 'connect-channel-instagram');
+ waitFor($page, '@connect-channel-instagram');
$page->click('@connect-channel-instagram');
- waitForConnectDialogTestId($page, 'instagram-connect-facebook-card');
+ waitFor($page, '@instagram-connect-facebook-card');
$stacked = $page->script(<<<'JS'
(() => {
@@ -372,12 +345,12 @@ test('connect through facebook on the instagram step leaves for the facebook log
function openTelegramConnectStep(): mixed
{
$page = visit(route('app.workspace.channels'));
- waitForConnectDialogTestId($page, 'channels-empty-connect');
+ waitFor($page, '@channels-empty-connect');
$page->script('window.__copied = []; navigator.clipboard.writeText = async (text) => { window.__copied.push(text); }; true;');
$page->click('@channels-empty-connect');
- waitForConnectDialogTestId($page, 'connect-channel-telegram');
+ waitFor($page, '@connect-channel-telegram');
$page->click('@connect-channel-telegram');
- waitForConnectDialogTestId($page, 'telegram-connect-command');
+ waitFor($page, '@telegram-connect-command');
return $page;
}
@@ -416,7 +389,7 @@ test('the telegram step shows its instructions, copies and regenerates the comma
$copiedCommand = $page->script('document.querySelector(\'[data-testid="telegram-connect-command"]\').textContent.trim()');
$page->click('@telegram-connect-copy');
- waitForConnectDialogTestId($page, 'telegram-connect-copied');
+ waitFor($page, '@telegram-connect-copied');
$page->assertSeeIn('@telegram-connect-copied', trans('common.actions.copied'))
->assertMissing('@telegram-connect-copy')
@@ -428,15 +401,7 @@ test('the telegram step shows its instructions, copies and regenerates the comma
$first = $page->script('document.querySelector(\'[data-testid="telegram-connect-command"]\').textContent.trim()');
$page->click('@telegram-connect-regenerate');
- $page->script(<<<JS
- (async () => {
- for (let i = 0; i < 100; i++) {
- const el = document.querySelector('[data-testid="telegram-connect-command"]');
- if (el && el.textContent.trim() !== '{$first}') return;
- await new Promise((r) => setTimeout(r, 50));
- }
- })();
- JS);
+ waitForState($page, '@telegram-connect-command', "element.textContent.trim() !== '{$first}'");
$second = $page->script('document.querySelector(\'[data-testid="telegram-connect-command"]\').textContent.trim()');
@@ -444,7 +409,7 @@ test('the telegram step shows its instructions, copies and regenerates the comma
$page->assertVisible('@telegram-connect-waiting')->assertNoJavaScriptErrors();
$page->click('@telegram-connect-help');
- waitForConnectDialogTestId($page, 'telegram-connect-help-bot-privacy');
+ waitFor($page, '@telegram-connect-help-bot-privacy');
$links = $page->script(<<<'JS'
(() => ['channel-admins', 'group-admins', 'bot-privacy'].map((key) => {
@@ -462,29 +427,22 @@ test('the telegram step shows its instructions, copies and regenerates the comma
$page->assertNoJavaScriptErrors();
$page->keys('@telegram-connect-help', 'Escape');
- $page->script(<<<'JS'
- (async () => {
- for (let i = 0; i < 100; i++) {
- if (!document.querySelector('[data-testid="telegram-connect-help-bot-privacy"]')) return;
- await new Promise((r) => setTimeout(r, 50));
- }
- })();
- JS);
+ waitForGone($page, '@telegram-connect-help-bot-privacy');
$page->keys('@connect-channel-back', 'Escape');
- waitForConnectDialogTestId($page, 'connect-channel-exit-confirm');
+ waitFor($page, '@connect-channel-exit-confirm');
$page->assertSeeIn('@connect-channel-exit-confirm', trans('channels.dialog.exit_confirm.title', ['network' => 'Telegram']));
$page->keys('@connect-channel-exit-continue', 'Escape');
- waitForConnectDialogTestId($page, 'connect-channel-back');
+ waitFor($page, '@connect-channel-back');
$page->assertMissing('@connect-channel-exit-confirm')
->assertVisible('@connect-channel-dialog')
->assertVisible('@connect-channel-back');
$page->keys('@connect-channel-back', 'Escape');
- waitForConnectDialogTestId($page, 'connect-channel-exit-leave');
+ waitFor($page, '@connect-channel-exit-leave');
$page->click('@connect-channel-exit-leave');
$page->assertMissing('@connect-channel-dialog')->assertNoJavaScriptErrors();
@@ -494,9 +452,9 @@ test('closing the network list does not ask for confirmation', function () {
$this->actingAs(connectDialogAdmin());
$page = visit(route('app.workspace.channels'));
- waitForConnectDialogTestId($page, 'channels-empty-connect');
+ waitFor($page, '@channels-empty-connect');
$page->click('@channels-empty-connect');
- waitForConnectDialogTestId($page, 'channel-platform-grid');
+ waitFor($page, '@channel-platform-grid');
$page->click('@dialog-close');
$page->assertMissing('@connect-channel-dialog')
diff --git a/tests/Browser/ConnectConfirmationTest.php b/tests/Browser/ConnectConfirmationTest.php
index 7f748dd70..b6d206eab 100644
--- a/tests/Browser/ConnectConfirmationTest.php
+++ b/tests/Browser/ConnectConfirmationTest.php
@@ -12,16 +12,7 @@ use Laravel\Socialite\Two\User as SocialiteUser;
function waitForConnectConfirmTestId(mixed $page, string $testId): void
{
- $page->script(<<<JS
- (async () => {
- const sel = '[data-testid="{$testId}"]';
- for (let i = 0; i < 160; i++) {
- const el = document.querySelector(sel);
- if (el && el.getBoundingClientRect().height > 0) return;
- await new Promise((r) => setTimeout(r, 50));
- }
- })();
- JS);
+ waitFor($page, "@{$testId}");
waitForWebFonts($page);
}
diff --git a/tests/Browser/ConnectSwitchAccountTest.php b/tests/Browser/ConnectSwitchAccountTest.php
index 11ca6d47e..bdb25548a 100644
--- a/tests/Browser/ConnectSwitchAccountTest.php
+++ b/tests/Browser/ConnectSwitchAccountTest.php
@@ -10,16 +10,7 @@ use Laravel\Socialite\Two\User as SocialiteUser;
function waitForSwitchAccountTestId(mixed $page, string $testId): void
{
- $page->script(<<<JS
- (async () => {
- const sel = '[data-testid="{$testId}"]';
- for (let i = 0; i < 160; i++) {
- const el = document.querySelector(sel);
- if (el && el.getBoundingClientRect().height > 0) return;
- await new Promise((r) => setTimeout(r, 50));
- }
- })();
- JS);
+ waitFor($page, "@{$testId}");
waitForWebFonts($page);
}
diff --git a/tests/Browser/CreateFeedsTest.php b/tests/Browser/CreateFeedsTest.php
index d81fd5649..4bade6129 100644
--- a/tests/Browser/CreateFeedsTest.php
+++ b/tests/Browser/CreateFeedsTest.php
@@ -14,54 +14,6 @@ use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Queue;
use Illuminate\Support\Facades\Storage;
-function waitForCreateFeedsTestId(mixed $page, string $testId): void
-{
- $page->script(<<<JS
- (async () => {
- for (let attempt = 0; attempt < 200; attempt++) {
- if (document.querySelector('[data-testid="{$testId}"]')?.getBoundingClientRect().height > 0) return;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })();
- JS);
-}
-
-function waitForCreateFeedsCondition(mixed $page, string $condition): void
-{
- $page->script(<<<JS
- (async () => {
- for (let attempt = 0; attempt < 200; attempt++) {
- if ({$condition}) return;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })();
- JS);
-}
-
-/**
- * Dialogs animate in; a click that lands before the animation settles is swallowed.
- */
-function waitForCreateFeedsDialog(mixed $page, string $testId): void
-{
- $page->script(<<<JS
- (async () => {
- for (let attempt = 0; attempt < 200; attempt++) {
- const dialog = document.querySelector('[data-testid="{$testId}"]');
- if (dialog?.getAttribute('data-state') === 'open'
- && dialog.getAnimations().every((animation) => animation.playState !== 'running')) return;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })();
- JS);
-}
-
-function waitForCreateFeedsDatabase(mixed $page, Closure $condition): void
-{
- for ($attempt = 0; $attempt < 50 && ! $condition(); $attempt++) {
- $page->script('new Promise((resolve) => setTimeout(resolve, 100))');
- }
-}
-
function createFeedsToastCount(mixed $page): int
{
return $page->script("document.querySelectorAll('[data-sonner-toast]').length");
@@ -123,9 +75,9 @@ test('a feed chip opens that feed with only its items', function () {
$this->actingAs($user);
$page = visit(route('app.create.feeds.index'));
- waitForCreateFeedsTestId($page, "feeds-chip-feed-{$first->id}");
+ waitFor($page, "@feeds-chip-feed-{$first->id}");
$page->click("@feeds-chip-feed-{$first->id}");
- waitForCreateFeedsTestId($page, 'feeds-scope-menu');
+ waitFor($page, '@feeds-scope-menu');
expect($page->script('window.location.pathname'))->toBe(route('app.create.feeds.show', $first, false));
@@ -144,7 +96,7 @@ test('hovering an item reveals its actions and create post opens the composer wi
$this->actingAs($user);
$page = visit(route('app.create.feeds.index'));
- waitForCreateFeedsTestId($page, "feed-item-{$item->id}");
+ waitFor($page, "@feed-item-{$item->id}");
$item->update(['image_url' => 'https://93.184.216.34/image.png']);
$page->hover("@feed-item-{$item->id}")
@@ -154,8 +106,8 @@ test('hovering an item reveals its actions and create post opens the composer wi
->assertVisible("@feed-item-save-idea-{$item->id}");
$page->click("@feed-item-create-post-{$item->id}");
- waitForCreateFeedsTestId($page, 'composer-base-content');
- waitForCreateFeedsTestId($page, 'composer-media-item');
+ waitFor($page, '@composer-base-content');
+ waitFor($page, '@composer-media-item');
$page->assertVisible('@post-composer-dialog')
->assertValue('@composer-base-content', "Launch notes\n\nhttps://93.184.216.34/launch")
@@ -174,11 +126,11 @@ test('save as idea creates an unassigned idea with the imported image and shows
$this->actingAs($user);
$page = visit(route('app.create.feeds.index'));
- waitForCreateFeedsTestId($page, "feed-item-{$item->id}");
+ waitFor($page, "@feed-item-{$item->id}");
$item->update(['image_url' => 'https://93.184.216.34/image.png']);
$page->hover("@feed-item-{$item->id}")->click("@feed-item-save-idea-{$item->id}");
- waitForCreateFeedsTestId($page, "feed-item-saved-{$item->id}");
+ waitFor($page, "@feed-item-saved-{$item->id}");
$page->assertVisible("@feed-item-saved-{$item->id}")
->assertMissing("@feed-item-save-idea-{$item->id}")
@@ -203,58 +155,59 @@ test('the scope menu renames in a dialog, moves into a collection and back, and
$this->actingAs($user);
$page = visit(route('app.create.feeds.show', $feed));
- waitForCreateFeedsTestId($page, 'feeds-scope-menu');
+ waitFor($page, '@feeds-scope-menu');
$page->click('@feeds-scope-menu');
- waitForCreateFeedsTestId($page, 'feeds-rename');
+ waitFor($page, '@feeds-rename');
$page->click('@feeds-rename');
- waitForCreateFeedsDialog($page, 'feeds-rename-dialog');
+ waitForOpen($page, '@feeds-rename-dialog');
expect($page->script("document.querySelector('[data-testid=\"feeds-rename-dialog-input\"]').value"))->toBe('Original');
$page->type('@feeds-rename-dialog-input', 'Renamed')->click('@feeds-rename-dialog-submit');
- waitForCreateFeedsCondition($page, "document.querySelector('[data-testid=\"feeds-chip-feed-{$feed->id}\"]')?.textContent.includes('Renamed') && !document.querySelector('[data-testid=\"feeds-rename-dialog\"]')");
+ waitForText($page, "@feeds-chip-feed-{$feed->id}", 'Renamed');
+ waitForGone($page, '@feeds-rename-dialog');
$page->assertSeeIn("@feeds-chip-feed-{$feed->id}", 'Renamed');
expect($feed->refresh()->custom_title)->toBe('Renamed');
$page->click('@feeds-scope-menu');
- waitForCreateFeedsTestId($page, 'feeds-rename');
+ waitFor($page, '@feeds-rename');
$page->click('@feeds-rename');
- waitForCreateFeedsDialog($page, 'feeds-rename-dialog');
+ waitForOpen($page, '@feeds-rename-dialog');
$page->type('@feeds-rename-dialog-input', 'Discarded')->click('@feeds-rename-dialog-cancel');
- waitForCreateFeedsCondition($page, "!document.querySelector('[data-testid=\"feeds-rename-dialog\"]')");
+ waitForGone($page, '@feeds-rename-dialog');
$page->assertSeeIn('@feeds-scope-name', 'Renamed');
expect($feed->refresh()->custom_title)->toBe('Renamed');
$page->click('@feeds-scope-menu');
- waitForCreateFeedsTestId($page, 'feeds-move-to');
+ waitFor($page, '@feeds-move-to');
$page->click('@feeds-move-to');
- waitForCreateFeedsTestId($page, "feeds-move-to-{$collection->id}");
+ waitFor($page, "@feeds-move-to-{$collection->id}");
$page->click("@feeds-move-to-{$collection->id}");
- waitForCreateFeedsCondition($page, "!document.querySelector('[data-testid=\"feeds-chip-feed-{$feed->id}\"]')");
+ waitForGone($page, "@feeds-chip-feed-{$feed->id}");
expect($feed->refresh()->rss_feed_collection_id)->toBe($collection->id)
->and($page->script("!!document.querySelector('[data-testid=\"feeds-collection-chips\"]')"))->toBeFalse();
$page->click('@feeds-scope-menu');
- waitForCreateFeedsTestId($page, 'feeds-move-to');
+ waitFor($page, '@feeds-move-to');
$page->click('@feeds-move-to');
- waitForCreateFeedsTestId($page, 'feeds-move-to-none');
+ waitFor($page, '@feeds-move-to-none');
$page->click('@feeds-move-to-none');
- waitForCreateFeedsCondition($page, "!!document.querySelector('[data-testid=\"feeds-chips\"] [data-testid=\"feeds-chip-feed-{$feed->id}\"]')");
+ waitForState($page, "@feeds-chips @feeds-chip-feed-{$feed->id}", 'true');
expect($feed->refresh()->rss_feed_collection_id)->toBeNull();
$page->click('@feeds-scope-menu');
- waitForCreateFeedsTestId($page, 'feeds-delete');
+ waitFor($page, '@feeds-delete');
$page->click('@feeds-delete');
- waitForCreateFeedsDialog($page, 'confirm-delete-modal');
+ waitForOpen($page, '@confirm-delete-modal');
$page->assertMissing('@confirm-delete-input')
->click('@confirm-delete-action');
- waitForCreateFeedsCondition($page, "window.location.pathname === '".route('app.create.feeds.index', [], false)."'");
+ waitForPath($page, route('app.create.feeds.index', [], false));
$page->assertMissing("@feeds-chip-feed-{$feed->id}")
->assertVisible("@feeds-chip-feed-{$other->id}")
@@ -270,33 +223,33 @@ test('the new menu creates a collection in a dialog and cancel adds nothing', fu
$this->actingAs($user);
$page = visit(route('app.create.feeds.index'));
- waitForCreateFeedsTestId($page, 'feeds-new-menu');
+ waitFor($page, '@feeds-new-menu');
$page->click('@feeds-new-menu');
- waitForCreateFeedsTestId($page, 'feeds-new-collection');
+ waitFor($page, '@feeds-new-collection');
$page->assertVisible('@feeds-explore')
->assertVisible('@feeds-new-collection');
expect($page->script("[...document.querySelectorAll('[role=\"menuitem\"]')].length"))->toBe(2);
$page->click('@feeds-new-collection');
- waitForCreateFeedsDialog($page, 'feeds-new-collection-dialog');
+ waitForOpen($page, '@feeds-new-collection-dialog');
$page->assertDisabled('@feeds-new-collection-dialog-submit')
->type('@feeds-new-collection-dialog-input', 'Research')
->click('@feeds-new-collection-dialog-submit');
- waitForCreateFeedsDatabase($page, fn (): bool => RssFeedCollection::query()->where('workspace_id', $workspace->id)->exists());
+ waitForDatabase($page, fn (): bool => RssFeedCollection::query()->where('workspace_id', $workspace->id)->exists());
$collection = RssFeedCollection::query()->where('workspace_id', $workspace->id)->sole();
- waitForCreateFeedsTestId($page, "feeds-chip-collection-{$collection->id}");
+ waitFor($page, "@feeds-chip-collection-{$collection->id}");
$page->assertSeeIn("@feeds-chip-collection-{$collection->id}", 'Research');
$page->click('@feeds-new-menu');
- waitForCreateFeedsTestId($page, 'feeds-new-collection');
+ waitFor($page, '@feeds-new-collection');
$page->click('@feeds-new-collection');
- waitForCreateFeedsDialog($page, 'feeds-new-collection-dialog');
+ waitForOpen($page, '@feeds-new-collection-dialog');
$page->type('@feeds-new-collection-dialog-input', 'Nope')->click('@feeds-new-collection-dialog-cancel');
- waitForCreateFeedsCondition($page, "!document.querySelector('[data-testid=\"feeds-new-collection-dialog\"]')");
+ waitForGone($page, '@feeds-new-collection-dialog');
$page->assertNoJavaScriptErrors();
expect(RssFeedCollection::query()->count())->toBe(1)
@@ -313,22 +266,22 @@ test('a collection chip opens a dropdown of its feeds and the label opens the co
$loose = createFeedsFeed($workspace, ['title' => 'Loose Feed']);
$page = visit(route('app.create.feeds.index'));
- waitForCreateFeedsTestId($page, "feeds-collection-menu-{$collection->id}");
+ waitFor($page, "@feeds-collection-menu-{$collection->id}");
expect($page->script("[...document.querySelectorAll('[data-testid=\"feeds-chips\"] > [data-testid]')].map((chip) => chip.dataset.testid)"))
->toBe(['feeds-chip-all', "feeds-chip-feed-{$outside->id}", "feeds-chip-feed-{$loose->id}", "feeds-collection-chip-{$collection->id}"]);
$page->click("@feeds-collection-menu-{$collection->id}");
- waitForCreateFeedsTestId($page, "feeds-collection-menu-item-{$inside->id}");
+ waitFor($page, "@feeds-collection-menu-item-{$inside->id}");
$page->assertVisible("@feeds-collection-menu-item-{$inside->id}")
->assertMissing("@feeds-collection-menu-item-{$outside->id}");
$page->click("@feeds-collection-menu-item-{$inside->id}");
- waitForCreateFeedsCondition($page, "window.location.pathname === '".route('app.create.feeds.show', $inside, false)."'");
- waitForCreateFeedsTestId($page, "feeds-chip-collection-{$collection->id}");
+ waitForPath($page, route('app.create.feeds.show', $inside, false));
+ waitFor($page, "@feeds-chip-collection-{$collection->id}");
$page->click("@feeds-chip-collection-{$collection->id}");
- waitForCreateFeedsCondition($page, "window.location.pathname === '".route('app.create.feeds.collections.show', $collection, false)."'");
+ waitForPath($page, route('app.create.feeds.collections.show', $collection, false));
$page->assertNoJavaScriptErrors();
});
@@ -347,15 +300,15 @@ test('add feed from the collection menu lands the feed in that collection', func
$this->actingAs($user);
$page = visit(route('app.create.feeds.collections.show', $collection));
- waitForCreateFeedsTestId($page, 'feeds-scope-menu');
+ waitFor($page, '@feeds-scope-menu');
$page->click('@feeds-scope-menu');
- waitForCreateFeedsTestId($page, 'feeds-add-to-collection');
+ waitFor($page, '@feeds-add-to-collection');
$page->click('@feeds-add-to-collection');
- waitForCreateFeedsTestId($page, 'feeds-collection-add-feed');
+ waitFor($page, '@feeds-collection-add-feed');
$page->click('@feeds-collection-add-feed');
- waitForCreateFeedsDialog($page, 'feeds-add-dialog');
+ waitForOpen($page, '@feeds-add-dialog');
$page->type('@feeds-add-url', 'http://93.184.216.34/feed.xml')->click('@feeds-add-submit');
- waitForCreateFeedsDatabase($page, fn (): bool => RssFeed::query()->where('url', 'http://93.184.216.34/feed.xml')->exists());
+ waitForDatabase($page, fn (): bool => RssFeed::query()->where('url', 'http://93.184.216.34/feed.xml')->exists());
expect(RssFeed::query()->where('url', 'http://93.184.216.34/feed.xml')->sole()->rss_feed_collection_id)->toBe($collection->id);
$page->assertNoJavaScriptErrors();
@@ -376,15 +329,15 @@ test('explore from the collection menu adds the directory feed into that collect
$this->actingAs($user);
$page = visit(route('app.create.feeds.collections.show', $collection));
- waitForCreateFeedsTestId($page, 'feeds-scope-menu');
+ waitFor($page, '@feeds-scope-menu');
$page->click('@feeds-scope-menu');
- waitForCreateFeedsTestId($page, 'feeds-add-to-collection');
+ waitFor($page, '@feeds-add-to-collection');
$page->click('@feeds-add-to-collection');
- waitForCreateFeedsTestId($page, 'feeds-collection-explore');
+ waitFor($page, '@feeds-collection-explore');
$page->click('@feeds-collection-explore');
- waitForCreateFeedsDialog($page, 'feeds-explore-dialog');
+ waitForOpen($page, '@feeds-explore-dialog');
$page->click('@feeds-explore-add-0');
- waitForCreateFeedsTestId($page, 'feeds-explore-remove-0');
+ waitFor($page, '@feeds-explore-remove-0');
expect(RssFeed::query()->where('url', 'http://93.184.216.34/feed.xml')->sole()->rss_feed_collection_id)->toBe($collection->id);
$page->assertNoJavaScriptErrors();
@@ -404,9 +357,9 @@ test('the add dialog adds a feed, and shows blocked and duplicate errors inline'
$this->actingAs($user);
$page = visit(route('app.create.feeds.index'));
- waitForCreateFeedsTestId($page, 'feeds-new');
+ waitFor($page, '@feeds-new');
$page->click('@feeds-new');
- waitForCreateFeedsDialog($page, 'feeds-add-dialog');
+ waitForOpen($page, '@feeds-add-dialog');
$page->assertVisible('@feeds-add-url')
->assertDisabled('@feeds-add-submit');
@@ -414,19 +367,19 @@ test('the add dialog adds a feed, and shows blocked and duplicate errors inline'
->and($page->script("document.querySelector('[data-testid=\"feeds-add-cancel\"]').compareDocumentPosition(document.querySelector('[data-testid=\"feeds-add-submit\"]')) & Node.DOCUMENT_POSITION_FOLLOWING"))->toBeGreaterThan(0);
$page->type('@feeds-add-url', 'http://127.0.0.1/feed.xml')->click('@feeds-add-submit');
- waitForCreateFeedsTestId($page, 'feeds-add-error');
+ waitFor($page, '@feeds-add-error');
$page->assertSeeIn('@feeds-add-error', __('create.feeds.errors.blocked_url'));
$page->clear('@feeds-add-url')->type('@feeds-add-url', 'https://existing.example.com/feed/')->click('@feeds-add-submit');
- waitForCreateFeedsCondition($page, "document.querySelector('[data-testid=\"feeds-add-error\"]')?.textContent.includes(".json_encode(__('create.feeds.errors.already_added')).')');
+ waitForText($page, '@feeds-add-error', __('create.feeds.errors.already_added'));
$page->assertSeeIn('@feeds-add-error', __('create.feeds.errors.already_added'));
$page->clear('@feeds-add-url')->type('@feeds-add-url', 'http://93.184.216.34/feed.xml')->click('@feeds-add-submit');
- waitForCreateFeedsDatabase($page, fn (): bool => RssFeed::query()->where('url', 'http://93.184.216.34/feed.xml')->exists());
+ waitForDatabase($page, fn (): bool => RssFeed::query()->where('url', 'http://93.184.216.34/feed.xml')->exists());
$feed = RssFeed::query()->where('url', 'http://93.184.216.34/feed.xml')->sole();
- waitForCreateFeedsCondition($page, "window.location.pathname === '".route('app.create.feeds.show', $feed, false)."'");
- waitForCreateFeedsTestId($page, "feeds-chip-feed-{$feed->id}");
+ waitForPath($page, route('app.create.feeds.show', $feed, false));
+ waitFor($page, "@feeds-chip-feed-{$feed->id}");
$page->assertMissing('@feeds-add-dialog')
->assertSeeIn('@feeds-scope-name', 'Fresh Blog')
@@ -448,34 +401,34 @@ test('explore switches categories, adds a directory feed and offers the trash fo
$this->actingAs($user);
$page = visit(route('app.create.feeds.index'));
- waitForCreateFeedsTestId($page, 'feeds-new-menu');
+ waitFor($page, '@feeds-new-menu');
$page->click('@feeds-new-menu');
- waitForCreateFeedsTestId($page, 'feeds-explore');
+ waitFor($page, '@feeds-explore');
$page->click('@feeds-explore');
- waitForCreateFeedsDialog($page, 'feeds-explore-dialog');
+ waitForOpen($page, '@feeds-explore-dialog');
$page->assertAttribute('@feeds-explore-category-favorites', 'aria-selected', 'true')
->assertVisible('@feeds-explore-grid-favorites');
$page->click('@feeds-explore-add-0');
- waitForCreateFeedsTestId($page, 'feeds-explore-remove-0');
+ waitFor($page, '@feeds-explore-remove-0');
$page->assertVisible('@feeds-explore-dialog')->assertMissing('@feeds-explore-add-0');
expect(RssFeed::query()->where('workspace_id', $workspace->id)->where('url', 'http://93.184.216.34/feed.xml')->exists())->toBeTrue()
->and(createFeedsToastCount($page))->toBe(0);
$page->click('@feeds-explore-category-tech');
- waitForCreateFeedsTestId($page, 'feeds-explore-grid-tech');
+ waitFor($page, '@feeds-explore-grid-tech');
$page->assertVisible('@feeds-explore-remove-1')
->assertMissing('@feeds-explore-add-1')
->assertVisible('@feeds-explore-add-0');
$page->click('@feeds-explore-remove-1');
- waitForCreateFeedsDialog($page, 'confirm-delete-modal');
+ waitForOpen($page, '@confirm-delete-modal');
$page->assertMissing('@confirm-delete-input')->click('@confirm-delete-action');
- waitForCreateFeedsDatabase($page, fn (): bool => ! RssFeed::query()->whereKey($verge->id)->exists());
- waitForCreateFeedsTestId($page, 'feeds-explore-add-1');
+ waitForDatabase($page, fn (): bool => ! RssFeed::query()->whereKey($verge->id)->exists());
+ waitFor($page, '@feeds-explore-add-1');
$page->assertVisible('@feeds-explore-dialog')
->assertVisible('@feeds-explore-add-1')
@@ -491,9 +444,9 @@ test('refresh inside the cooldown keeps the header and shows no toast', function
$this->actingAs($user);
$page = visit(route('app.create.feeds.index'));
- waitForCreateFeedsTestId($page, 'feeds-refresh');
+ waitFor($page, '@feeds-refresh');
$page->click('@feeds-refresh');
- waitForCreateFeedsCondition($page, "!document.querySelector('[data-testid=\"feeds-refresh\"]').disabled");
+ waitForState($page, '@feeds-refresh', '!element.disabled');
$page->assertVisible('@feeds-last-refreshed')->assertNoJavaScriptErrors();
expect(createFeedsToastCount($page))->toBe(0)
@@ -517,23 +470,23 @@ test('explore opened from a feed keeps that feed url, stays there after a direct
$path = route('app.create.feeds.show', $feed, false);
$page = visit(route('app.create.feeds.show', $feed));
- waitForCreateFeedsTestId($page, 'feeds-new-menu');
+ waitFor($page, '@feeds-new-menu');
$page->click('@feeds-new-menu');
- waitForCreateFeedsTestId($page, 'feeds-explore');
+ waitFor($page, '@feeds-explore');
$page->click('@feeds-explore');
- waitForCreateFeedsDialog($page, 'feeds-explore-dialog');
+ waitForOpen($page, '@feeds-explore-dialog');
expect($page->script('window.location.pathname'))->toBe($path)
->and($page->script('window.location.search'))->toBe('');
$page->click('@feeds-explore-add-0');
- waitForCreateFeedsTestId($page, 'feeds-explore-remove-0');
+ waitFor($page, '@feeds-explore-remove-0');
expect($page->script('window.location.pathname'))->toBe($path);
$page->assertSeeIn('@feeds-scope-name', 'Scoped source');
$page->keys('@feeds-explore-dialog', 'Escape');
- waitForCreateFeedsCondition($page, "!document.querySelector('[data-testid=\"feeds-explore-dialog\"]')");
+ waitForGone($page, '@feeds-explore-dialog');
expect($page->script('window.location.pathname'))->toBe($path)
->and($page->script('window.location.search'))->toBe('');
@@ -547,15 +500,15 @@ test('the add dialog opened from a collection keeps the collection url', functio
$this->actingAs($user);
$page = visit(route('app.create.feeds.collections.show', $collection));
- waitForCreateFeedsTestId($page, 'feeds-new');
+ waitFor($page, '@feeds-new');
$page->click('@feeds-new');
- waitForCreateFeedsDialog($page, 'feeds-add-dialog');
+ waitForOpen($page, '@feeds-add-dialog');
expect($page->script('window.location.pathname'))->toBe(route('app.create.feeds.collections.show', $collection, false))
->and($page->script('window.location.search'))->toBe('');
$page->click('@feeds-add-cancel');
- waitForCreateFeedsCondition($page, "!document.querySelector('[data-testid=\"feeds-add-dialog\"]')");
+ waitForGone($page, '@feeds-add-dialog');
expect($page->script('window.location.search'))->toBe('');
$page->assertNoJavaScriptErrors();
@@ -567,7 +520,7 @@ test('explore category tabs are a complete tabs pattern with arrow key navigatio
$page = visit(route('app.create.feeds.index'));
openCreateFeedsExploreFromSplitButton($page);
- waitForCreateFeedsTestId($page, 'feeds-explore-category-favorites');
+ waitFor($page, '@feeds-explore-category-favorites');
$page->assertAttribute('@feeds-explore-category-favorites', 'tabindex', '0')
->assertAttribute('@feeds-explore-grid-favorites', 'role', 'tabpanel')
@@ -575,7 +528,7 @@ test('explore category tabs are a complete tabs pattern with arrow key navigatio
$page->script("document.querySelector('[data-testid=\"feeds-explore-category-favorites\"]').focus()");
$page->keys('@feeds-explore-category-favorites', 'ArrowRight');
- waitForCreateFeedsCondition($page, "document.querySelector('[role=\"tab\"][aria-selected=\"true\"]')?.id !== 'feeds-explore-tab-favorites'");
+ waitForCondition($page, "document.querySelector('[role=\"tab\"][aria-selected=\"true\"]')?.id !== 'feeds-explore-tab-favorites'");
expect($page->script("document.activeElement.getAttribute('role')"))->toBe('tab')
->and($page->script("document.activeElement.getAttribute('aria-selected')"))->toBe('true')
@@ -594,7 +547,7 @@ test('the feeds page fits a 390px viewport with scrolling chips, a usable split
$this->actingAs($user);
$page = visit(route('app.create.feeds.index'))->resize(390, 844);
- waitForCreateFeedsTestId($page, "feed-item-{$item->id}");
+ waitFor($page, "@feed-item-{$item->id}");
expect($page->script('document.documentElement.scrollWidth - window.innerWidth'))->toBeLessThanOrEqual(2)
->and($page->script("(() => { const nav = document.querySelector('[data-testid=\"feeds-chips\"]'); return nav.scrollWidth > nav.clientWidth && getComputedStyle(nav).overflowX === 'auto'; })()"))->toBeTrue()
@@ -606,33 +559,33 @@ test('the feeds page fits a 390px viewport with scrolling chips, a usable split
expect($page->script("(() => { const r = document.querySelector('[data-testid=\"feed-item-save-idea-{$item->id}\"]').getBoundingClientRect(); return r.right <= window.innerWidth && r.left >= 0; })()"))->toBeTrue();
$page->click('@feeds-new');
- waitForCreateFeedsDialog($page, 'feeds-add-dialog');
+ waitForOpen($page, '@feeds-add-dialog');
$page->assertVisible('@feeds-add-url')->assertNoJavaScriptErrors();
});
function openCreateFeedsExploreFromSplitButton(mixed $page): void
{
- waitForCreateFeedsTestId($page, 'feeds-new-menu');
+ waitFor($page, '@feeds-new-menu');
$page->click('@feeds-new-menu');
- waitForCreateFeedsTestId($page, 'feeds-explore');
+ waitFor($page, '@feeds-explore');
$page->click('@feeds-explore');
- waitForCreateFeedsDialog($page, 'feeds-explore-dialog');
+ waitForOpen($page, '@feeds-explore-dialog');
}
function openCreateFeedsExploreFromCollectionMenu(mixed $page): void
{
- waitForCreateFeedsTestId($page, 'feeds-scope-menu');
+ waitFor($page, '@feeds-scope-menu');
$page->click('@feeds-scope-menu');
- waitForCreateFeedsTestId($page, 'feeds-add-to-collection');
+ waitFor($page, '@feeds-add-to-collection');
$page->click('@feeds-add-to-collection');
- waitForCreateFeedsTestId($page, 'feeds-collection-explore');
+ waitFor($page, '@feeds-collection-explore');
$page->click('@feeds-collection-explore');
- waitForCreateFeedsDialog($page, 'feeds-explore-dialog');
+ waitForOpen($page, '@feeds-explore-dialog');
}
function assertCreateFeedsExploreClosed(mixed $page, string $path): void
{
- waitForCreateFeedsCondition($page, "!document.querySelector('[data-testid=\"feeds-explore-dialog\"]')");
+ waitForGone($page, '@feeds-explore-dialog');
$page->assertMissing('@feeds-explore-dialog');
expect($page->script('window.location.pathname'))->toBe($path)
@@ -658,15 +611,15 @@ test('explore closes with the close button, escape and an outside click wherever
openCreateFeedsExploreFromSplitButton($page);
$page->click('@feeds-explore-category-tech');
- waitForCreateFeedsTestId($page, 'feeds-explore-grid-tech');
+ waitFor($page, '@feeds-explore-grid-tech');
$page->click('@dialog-close');
assertCreateFeedsExploreClosed($page, $path);
openCreateFeedsExploreFromCollectionMenu($page);
$page->click('@feeds-explore-add-0');
- waitForCreateFeedsTestId($page, 'feeds-explore-remove-0');
+ waitFor($page, '@feeds-explore-remove-0');
$page->click('@feeds-explore-category-tech');
- waitForCreateFeedsTestId($page, 'feeds-explore-grid-tech');
+ waitFor($page, '@feeds-explore-grid-tech');
$page->keys('@feeds-explore-dialog', 'Escape');
assertCreateFeedsExploreClosed($page, $path);
@@ -694,16 +647,16 @@ test('closing explore keeps the item list loading further pages without duplicat
$scrollToEnd = "document.querySelector('[data-testid=\"feeds-scroll\"]').scrollTop = 100000";
$page = visit(route('app.create.feeds.index'));
- waitForCreateFeedsTestId($page, 'feeds-items');
+ waitFor($page, '@feeds-items');
$page->script($scrollToEnd);
- waitForCreateFeedsTestId($page, 'feeds-caught-up');
+ waitFor($page, '@feeds-caught-up');
openCreateFeedsExploreFromSplitButton($page);
$page->click('@dialog-close');
assertCreateFeedsExploreClosed($page, route('app.create.feeds.index', [], false));
$page->script($scrollToEnd);
- waitForCreateFeedsCondition($page, "{$articles}.length === 45");
+ waitForCondition($page, "{$articles}.length === 45");
expect($page->script("{$articles}.length"))->toBe(45)
->and($page->script("new Set({$articles}.map((article) => article.dataset.testid)).size"))->toBe(45);
@@ -719,7 +672,7 @@ test('the create tabs stay put while the chips scroll away with the feed list',
$this->actingAs($user);
$page = visit(route('app.create.feeds.index'))->resize(1280, 700);
- waitForCreateFeedsTestId($page, 'feeds-items');
+ waitFor($page, '@feeds-items');
$tabsTop = "document.querySelector('[data-testid=\"create-tabs\"]').getBoundingClientRect().top";
$chipsBottom = "document.querySelector('[data-testid=\"feeds-chips\"]').getBoundingClientRect().bottom";
@@ -727,7 +680,7 @@ test('the create tabs stay put while the chips scroll away with the feed list',
$before = $page->script($tabsTop);
$page->script("document.querySelector('[data-testid=\"feeds-scroll\"]').scrollTop = 600");
- waitForCreateFeedsCondition($page, "document.querySelector('[data-testid=\"feeds-scroll\"]').scrollTop > 0");
+ waitForState($page, '@feeds-scroll', 'element.scrollTop > 0');
expect($page->script($tabsTop))->toBe($before)
->and($page->script("{$chipsBottom} <= {$tabsBottom}"))->toBeTrue();
diff --git a/tests/Browser/CreateIdeaEditorTest.php b/tests/Browser/CreateIdeaEditorTest.php
index 19140e46e..40b4f70c5 100644
--- a/tests/Browser/CreateIdeaEditorTest.php
+++ b/tests/Browser/CreateIdeaEditorTest.php
@@ -18,53 +18,7 @@ function waitForCreateIdeaEditorTestId(mixed $page, string $testId, string $text
{
$expected = json_encode($text);
- $page->script(<<<JS
- (async () => {
- for (let attempt = 0; attempt < 200; attempt++) {
- const element = document.querySelector('[data-testid="{$testId}"]');
- if (element?.getBoundingClientRect().height > 0
- && (element.value ?? element.textContent ?? '').includes({$expected})) return;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })();
- JS);
-}
-
-function waitForCreateIdeaEditorCondition(mixed $page, string $condition): void
-{
- $page->script(<<<JS
- (async () => {
- for (let attempt = 0; attempt < 200; attempt++) {
- if ({$condition}) return;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })();
- JS);
-}
-
-function waitForCreateIdeaEditorDatabase(mixed $page, Closure $condition): void
-{
- for ($attempt = 0; $attempt < 50 && ! $condition(); $attempt++) {
- $page->script('new Promise((resolve) => setTimeout(resolve, 100))');
- }
-}
-
-/**
- * The editor opens as an animated dialog; a click that lands before the
- * animation settles is swallowed.
- */
-function waitForCreateIdeaEditorDialog(mixed $page): void
-{
- $page->script(<<<'JS'
- (async () => {
- for (let attempt = 0; attempt < 200; attempt++) {
- const dialog = document.querySelector('[data-testid="idea-editor"]');
- if (dialog?.getAttribute('data-state') === 'open'
- && dialog.getAnimations().every((animation) => animation.playState !== 'running')) return;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })();
- JS);
+ waitForState($page, "@{$testId}", "element.getBoundingClientRect().height > 0 && (element.value ?? element.textContent ?? '').includes({$expected})");
}
/**
@@ -100,29 +54,29 @@ test('a label created from the idea editor is selected and saved with the idea',
$this->actingAs($user);
$page = visit(route('app.create.ideas.create'));
- waitForCreateIdeaEditorDialog($page);
+ waitForOpen($page, '@idea-editor');
$page->fill('@idea-editor-title', 'Labelled idea')
->click('@idea-editor-labels');
- waitForCreateIdeaEditorTestId($page, 'idea-editor-label-empty-create');
+ waitFor($page, '@idea-editor-label-empty-create');
$page->click('@idea-editor-label-empty-create');
- waitForCreateIdeaEditorTestId($page, 'idea-editor-label-new-name');
+ waitFor($page, '@idea-editor-label-new-name');
$page->fill('@idea-editor-label-new-name', 'Launch')
->click('@submit-idea-editor-label-new');
$label = null;
- waitForCreateIdeaEditorDatabase($page, function () use ($workspace, &$label): bool {
+ waitForDatabase($page, function () use ($workspace, &$label): bool {
$label = WorkspaceLabel::where('workspace_id', $workspace->id)->where('name', 'Launch')->first();
return $label !== null;
});
- waitForCreateIdeaEditorTestId($page, "idea-editor-label-checkbox-{$label->id}");
+ waitFor($page, "@idea-editor-label-checkbox-{$label->id}");
$page->assertScript("document.querySelector('[data-testid=\"idea-editor-label-checkbox-{$label->id}\"]').getAttribute('data-state')", 'checked')
->click('@idea-editor-labels')
->click('@idea-editor-save');
- waitForCreateIdeaEditorDatabase($page, fn (): bool => Idea::where('title', 'Labelled idea')->exists());
+ waitForDatabase($page, fn (): bool => Idea::where('title', 'Labelled idea')->exists());
$idea = Idea::where('title', 'Labelled idea')->sole();
expect($idea->labels()->pluck('workspace_labels.id')->all())->toBe([$label->id]);
@@ -135,31 +89,32 @@ test('a new idea is saved with its stage and label and the editor returns to the
$this->actingAs($user);
$page = visit(route('app.create.ideas.create'));
- waitForCreateIdeaEditorDialog($page);
+ waitForOpen($page, '@idea-editor');
$page->assertDisabled('@idea-editor-save')
->assertDisabled('@idea-editor-create-post')
->fill('@idea-editor-title', 'Spring launch')
->assertEnabled('@idea-editor-save')
->click('@idea-editor-stage');
- waitForCreateIdeaEditorTestId($page, "idea-editor-stage-option-{$stage->id}");
+ waitFor($page, "@idea-editor-stage-option-{$stage->id}");
$page->click("@idea-editor-stage-option-{$stage->id}")
->assertSeeIn('@idea-editor-stage', $stage->name)
->click('@idea-editor-labels');
- waitForCreateIdeaEditorTestId($page, "idea-editor-label-option-{$label->id}");
+ waitFor($page, "@idea-editor-label-option-{$label->id}");
$page->click("@idea-editor-label-option-{$label->id}")
->click('@idea-editor-labels')
->click('@idea-editor-save');
- waitForCreateIdeaEditorDatabase($page, fn (): bool => Idea::where('title', 'Spring launch')->exists());
+ waitForDatabase($page, fn (): bool => Idea::where('title', 'Spring launch')->exists());
$idea = Idea::where('title', 'Spring launch')->sole();
expect($idea->idea_stage_id)->toBe($stage->id)
->and($idea->labels()->pluck('workspace_labels.id')->all())->toBe([$label->id]);
$indexPath = parse_url(route('app.create.ideas.index'), PHP_URL_PATH);
- waitForCreateIdeaEditorCondition($page, "!document.querySelector('[data-testid=\"idea-editor\"]') && location.pathname === '{$indexPath}'");
- waitForCreateIdeaEditorTestId($page, "idea-card-{$idea->id}");
+ waitForGone($page, '@idea-editor');
+ waitForPath($page, $indexPath);
+ waitFor($page, "@idea-card-{$idea->id}");
expect($page->script('location.pathname'))->toBe($indexPath);
$page->assertMissing('@idea-editor')
@@ -173,18 +128,18 @@ test('an existing idea opens in the editor and saves its changes', function () {
$this->actingAs($user);
$page = visit(route('app.create.ideas.show', $idea));
- waitForCreateIdeaEditorDialog($page);
+ waitForOpen($page, '@idea-editor');
$page->assertValue('@idea-editor-title', 'Old title')
->assertValue('@idea-editor-body', 'Old body')
->fill('@idea-editor-body', 'New body')
->click('@idea-editor-save');
- waitForCreateIdeaEditorDatabase($page, fn (): bool => $idea->refresh()->body === 'New body');
+ waitForDatabase($page, fn (): bool => $idea->refresh()->body === 'New body');
expect($idea->refresh()->body)->toBe('New body')
->and($idea->title)->toBe('Old title');
- waitForCreateIdeaEditorCondition($page, "!document.querySelector('[data-testid=\"idea-editor\"]')");
+ waitForGone($page, '@idea-editor');
$page->assertMissing('@idea-editor')
->assertNoJavaScriptErrors();
});
@@ -251,24 +206,24 @@ test('an uploaded image blocks saving until it is ready, then the idea owns it',
$this->actingAs($user);
$page = visit(route('app.create.ideas.create'));
- waitForCreateIdeaEditorDialog($page);
- waitForCreateIdeaEditorTestId($page, 'idea-dropzone');
+ waitForOpen($page, '@idea-editor');
+ waitFor($page, '@idea-dropzone');
holdCreateIdeaEditorUploads($page);
$page->fill('@idea-editor-title', 'With a picture');
selectCreateIdeaEditorFile($page, 'idea-photo.png');
- waitForCreateIdeaEditorCondition($page, 'window.__ideaRequests.length === 1');
+ waitForCondition($page, 'window.__ideaRequests.length === 1');
$page->assertVisible('@idea-upload-item')
->assertDisabled('@idea-editor-save')
->assertDisabled('@idea-editor-create-post');
$page->script('window.__releaseIdeaRequests()');
- waitForCreateIdeaEditorTestId($page, 'idea-media-item');
+ waitFor($page, '@idea-media-item');
$page->assertMissing('@idea-upload-item')
->assertEnabled('@idea-editor-save')
->click('@idea-editor-save');
- waitForCreateIdeaEditorDatabase($page, fn (): bool => Idea::where('title', 'With a picture')->exists());
+ waitForDatabase($page, fn (): bool => Idea::where('title', 'With a picture')->exists());
$idea = Idea::where('title', 'With a picture')->sole();
$owned = $idea->ownedMedia()->sole();
@@ -277,17 +232,17 @@ test('an uploaded image blocks saving until it is ready, then the idea owns it',
->and($owned->original_filename)->toBe('idea-photo.png')
->and(Media::where('workspace_id', $workspace->id)->count())->toBe(1);
- waitForCreateIdeaEditorCondition($page, "document.querySelector('[data-testid=\"idea-card-{$idea->id}\"] img')?.getBoundingClientRect().height > 0");
+ waitFor($page, "@idea-card-{$idea->id} img");
expect($page->script("document.querySelector('[data-testid=\"idea-card-{$idea->id}\"] img').getAttribute('src')"))->toBe($owned->url);
$page = visit(route('app.create.ideas.show', $idea));
- waitForCreateIdeaEditorDialog($page);
- waitForCreateIdeaEditorTestId($page, 'idea-media-item');
+ waitForOpen($page, '@idea-editor');
+ waitFor($page, '@idea-media-item');
$page->click('@idea-remove-0')
->assertMissing('@idea-media-item')
->click('@idea-editor-save');
- waitForCreateIdeaEditorDatabase($page, fn (): bool => $idea->refresh()->media === []);
+ waitForDatabase($page, fn (): bool => $idea->refresh()->media === []);
expect($idea->refresh()->media)->toBe([])
->and(Media::find($owned->id))->toBeNull();
@@ -299,12 +254,12 @@ test('a failed upload blocks saving until it is removed', function () {
$this->actingAs($user);
$page = visit(route('app.create.ideas.create'));
- waitForCreateIdeaEditorDialog($page);
- waitForCreateIdeaEditorTestId($page, 'idea-dropzone');
+ waitForOpen($page, '@idea-editor');
+ waitFor($page, '@idea-dropzone');
holdCreateIdeaEditorUploads($page, 'fail');
$page->fill('@idea-editor-title', 'Failing upload');
selectCreateIdeaEditorFile($page, 'broken.png');
- waitForCreateIdeaEditorTestId($page, 'idea-upload-error');
+ waitFor($page, '@idea-upload-error');
$page->assertVisible('@idea-editor-upload-blocked')
->assertDisabled('@idea-editor-save')
@@ -322,18 +277,18 @@ test('a media error from the server lands on the tile it belongs to', function (
$this->actingAs($user);
$page = visit(route('app.create.ideas.create'));
- waitForCreateIdeaEditorDialog($page);
- waitForCreateIdeaEditorTestId($page, 'idea-dropzone');
+ waitForOpen($page, '@idea-editor');
+ waitFor($page, '@idea-dropzone');
$page->fill('@idea-editor-title', 'Two pictures');
selectCreateIdeaEditorFile($page, 'first.png');
- waitForCreateIdeaEditorCondition($page, "document.querySelectorAll('[data-testid=\"idea-media-item\"]').length === 1");
+ waitForCount($page, '@idea-media-item', 1);
selectCreateIdeaEditorFile($page, 'second.png');
- waitForCreateIdeaEditorCondition($page, "document.querySelectorAll('[data-testid=\"idea-media-item\"]').length === 2");
+ waitForCount($page, '@idea-media-item', 2);
Media::where('workspace_id', $workspace->id)->where('original_filename', 'second.png')->sole()->delete();
$page->click('@idea-editor-save');
- waitForCreateIdeaEditorTestId($page, 'idea-media-error-1');
+ waitFor($page, '@idea-media-error-1');
$page->assertVisible('@idea-media-error-1')
->assertMissing('@idea-media-error-0')
@@ -348,14 +303,15 @@ test('closing the editor aborts uploads in flight', function () {
$this->actingAs($user);
$page = visit(route('app.create.ideas.create'));
- waitForCreateIdeaEditorDialog($page);
- waitForCreateIdeaEditorTestId($page, 'idea-dropzone');
+ waitForOpen($page, '@idea-editor');
+ waitFor($page, '@idea-dropzone');
holdCreateIdeaEditorUploads($page);
selectCreateIdeaEditorFile($page, 'pending.png');
- waitForCreateIdeaEditorCondition($page, 'window.__ideaRequests.length === 1');
+ waitForCondition($page, 'window.__ideaRequests.length === 1');
$page->click('@idea-editor-cancel');
- waitForCreateIdeaEditorCondition($page, "!document.querySelector('[data-testid=\"idea-editor\"]') && window.__ideaAborted > 0");
+ waitForGone($page, '@idea-editor');
+ waitForCondition($page, 'window.__ideaAborted > 0');
expect($page->script('window.__ideaAborted'))->toBe(1);
$page->assertMissing('@idea-editor')
@@ -368,17 +324,17 @@ test('the dropzone is disabled while the idea saves', function () {
$this->actingAs($user);
$page = visit(route('app.create.ideas.create'));
- waitForCreateIdeaEditorDialog($page);
+ waitForOpen($page, '@idea-editor');
interceptCreateIdeaEditorRequests($page, route('app.create.ideas.store', absolute: false));
$page->fill('@idea-editor-title', 'Saving slowly')
->assertEnabled('@idea-dropzone')
->click('@idea-editor-save');
- waitForCreateIdeaEditorCondition($page, 'window.__ideaRequests.length === 1');
+ waitForCondition($page, 'window.__ideaRequests.length === 1');
$page->assertDisabled('@idea-dropzone');
$page->script('window.__releaseIdeaRequests()');
- waitForCreateIdeaEditorCondition($page, "!document.querySelector('[data-testid=\"idea-editor\"]')");
+ waitForGone($page, '@idea-editor');
$page->assertNoJavaScriptErrors();
});
@@ -387,8 +343,8 @@ test('the toolbar has no add button and the dropzone opens the file dialog', fun
$this->actingAs($user);
$page = visit(route('app.create.ideas.create'));
- waitForCreateIdeaEditorDialog($page);
- waitForCreateIdeaEditorTestId($page, 'idea-dropzone');
+ waitForOpen($page, '@idea-editor');
+ waitFor($page, '@idea-dropzone');
$page->script(<<<'JS'
(() => {
window.__ideaFileDialogOpened = 0;
@@ -409,25 +365,25 @@ test('the AI assistant rewrites and extends the body without a channel', functio
$this->actingAs($user);
$page = visit(route('app.create.ideas.create'));
- waitForCreateIdeaEditorDialog($page);
+ waitForOpen($page, '@idea-editor');
$page->fill('@idea-editor-body', 'Rough text')
->click('@idea-editor-ai');
- waitForCreateIdeaEditorTestId($page, 'writing-assistant-panel');
+ waitFor($page, '@writing-assistant-panel');
$page->assertMissing('@writing-assistant-channel')
->assertVisible('@writing-assistant-disclaimer')
->click('@writing-assistant-mode-rephrase');
- waitForCreateIdeaEditorTestId($page, 'writing-assistant-replace');
+ waitFor($page, '@writing-assistant-replace');
$page->click('@writing-assistant-replace')
->assertValue('@idea-editor-body', 'Sharper text');
PostWritingAssistant::fake(['New angle']);
$page->click('@writing-assistant-mode-generate');
- waitForCreateIdeaEditorTestId($page, 'writing-assistant-prompt');
+ waitFor($page, '@writing-assistant-prompt');
$page->fill('@writing-assistant-prompt', 'ideas for our spring sale')
->click('@writing-assistant-generate');
- waitForCreateIdeaEditorTestId($page, 'writing-assistant-insert');
+ waitFor($page, '@writing-assistant-insert');
$page->click('@writing-assistant-insert')
->assertValue('@idea-editor-body', "Sharper text\n\nNew angle")
->assertNoJavaScriptErrors();
@@ -441,7 +397,7 @@ test('create post closes the editor and opens the composer with the idea', funct
$this->actingAs($user);
$page = visit(route('app.create.ideas.show', $idea));
- waitForCreateIdeaEditorDialog($page);
+ waitForOpen($page, '@idea-editor');
$page->click('@idea-editor-create-post');
waitForCreateIdeaEditorTestId($page, 'composer-base-content', 'Hello');
@@ -465,9 +421,9 @@ test('generate ideas shows one idea, generates again and opens it unsaved in the
if ($size !== null) {
$page->resize(...$size);
}
- waitForCreateIdeaEditorTestId($page, 'ideas-generate');
+ waitFor($page, '@ideas-generate');
$page->click('@ideas-generate');
- waitForCreateIdeaEditorTestId($page, 'ideas-generate-dialog');
+ waitFor($page, '@ideas-generate-dialog');
$page->assertMissing('@ideas-generate-count')
->assertMissing('@ideas-generate-stage')
@@ -501,7 +457,7 @@ test('generate ideas shows one idea, generates again and opens it unsaved in the
&& $prompt->agent->business === 'A handmade ceramics studio');
$page->click('@ideas-generate-use');
- waitForCreateIdeaEditorDialog($page);
+ waitForOpen($page, '@idea-editor');
waitForCreateIdeaEditorTestId($page, 'idea-editor-title', 'Glaze of the week');
$page->assertMissing('@ideas-generate-dialog')
@@ -511,25 +467,25 @@ test('generate ideas shows one idea, generates again and opens it unsaved in the
expect(Idea::where('workspace_id', $workspace->id)->exists())->toBeFalse();
$page->click('@idea-editor-save');
- waitForCreateIdeaEditorDatabase($page, fn (): bool => Idea::where('workspace_id', $workspace->id)->exists());
+ waitForDatabase($page, fn (): bool => Idea::where('workspace_id', $workspace->id)->exists());
$idea = Idea::where('workspace_id', $workspace->id)->sole();
expect($idea->title)->toBe('Glaze of the week')
->and($idea->body)->toBe('Feature one glaze.')
->and($idea->idea_stage_id)->toBeNull();
- waitForCreateIdeaEditorCondition($page, "!document.querySelector('[data-testid=\"idea-editor\"]')");
- waitForCreateIdeaEditorTestId($page, 'ideas-new');
+ waitForGone($page, '@idea-editor');
+ waitFor($page, '@ideas-new');
$page->click('@ideas-new');
- waitForCreateIdeaEditorDialog($page);
+ waitForOpen($page, '@idea-editor');
$page->assertValue('@idea-editor-title', '')
->assertValue('@idea-editor-body', '');
$page->click('@idea-editor-cancel');
- waitForCreateIdeaEditorCondition($page, "!document.querySelector('[data-testid=\"idea-editor\"]')");
+ waitForGone($page, '@idea-editor');
$page->click('@ideas-generate');
- waitForCreateIdeaEditorTestId($page, 'ideas-generate-audience');
+ waitFor($page, '@ideas-generate-audience');
$page->assertValue('@ideas-generate-audience', '')
->assertValue('@ideas-generate-business', '')
@@ -549,9 +505,9 @@ test('generate ideas shows the payment required message inline when AI is denied
$this->actingAs($user);
$page = visit(route('app.create.ideas.index'));
- waitForCreateIdeaEditorTestId($page, 'ideas-generate');
+ waitFor($page, '@ideas-generate');
$page->click('@ideas-generate');
- waitForCreateIdeaEditorTestId($page, 'ideas-generate-dialog');
+ waitFor($page, '@ideas-generate-dialog');
$page->fill('@ideas-generate-business', 'A handmade ceramics studio')
->fill('@ideas-generate-audience', 'Home decor lovers')
->click('@ideas-generate-submit');
@@ -576,9 +532,9 @@ test('generate ideas shows the failure inline when the provider fails and a retr
$this->actingAs($user);
$page = visit(route('app.create.ideas.index'));
- waitForCreateIdeaEditorTestId($page, 'ideas-generate');
+ waitFor($page, '@ideas-generate');
$page->click('@ideas-generate');
- waitForCreateIdeaEditorTestId($page, 'ideas-generate-dialog');
+ waitFor($page, '@ideas-generate-dialog');
$page->fill('@ideas-generate-business', 'A handmade ceramics studio')
->fill('@ideas-generate-audience', 'Home decor lovers')
->click('@ideas-generate-submit');
@@ -590,7 +546,7 @@ test('generate ideas shows the failure inline when the provider fails and a retr
->click('@ideas-generate-submit');
waitForCreateIdeaEditorTestId($page, 'ideas-generate-result', 'Behind the kiln');
- waitForCreateIdeaEditorCondition($page, "!document.querySelector('[data-testid=\"ideas-generate-error\"]')");
+ waitForGone($page, '@ideas-generate-error');
$page->assertSeeIn('@ideas-generate-result', 'Show the firing process.')
->assertMissing('@ideas-generate-error')
@@ -603,7 +559,7 @@ test('the editor footer renders cancel, then create post, then save', function (
$this->actingAs($user);
$page = visit(route('app.create.ideas.create'));
- waitForCreateIdeaEditorDialog($page);
+ waitForOpen($page, '@idea-editor');
expect($page->script(<<<'JS'
(() => {
@@ -644,13 +600,14 @@ test('opening and closing an idea on the board reloads only the editor', functio
$this->actingAs($user);
$page = visit(route('app.create.ideas.index'));
- waitForCreateIdeaEditorTestId($page, "idea-card-{$idea->id}");
+ waitFor($page, "@idea-card-{$idea->id}");
recordCreateIdeaEditorInertiaRequests($page);
$page->click("@idea-card-{$idea->id}");
- waitForCreateIdeaEditorDialog($page);
+ waitForOpen($page, '@idea-editor');
$page->click('@idea-editor-cancel');
- waitForCreateIdeaEditorCondition($page, "!document.querySelector('[data-testid=\"idea-editor\"]') && window.__inertiaRequests.length >= 2");
+ waitForGone($page, '@idea-editor');
+ waitForCondition($page, 'window.__inertiaRequests.length >= 2');
expect($page->script('window.__inertiaRequests'))->toBe(['editor', 'editor']);
$page->assertMissing('@idea-editor')
@@ -663,13 +620,13 @@ test('saving an idea reloads the board with the change', function () {
$this->actingAs($user);
$page = visit(route('app.create.ideas.index'));
- waitForCreateIdeaEditorTestId($page, "idea-card-{$idea->id}");
+ waitFor($page, "@idea-card-{$idea->id}");
$page->click("@idea-card-{$idea->id}");
- waitForCreateIdeaEditorDialog($page);
+ waitForOpen($page, '@idea-editor');
$page->fill('@idea-editor-title', 'After')
->click('@idea-editor-save');
- waitForCreateIdeaEditorCondition($page, "!document.querySelector('[data-testid=\"idea-editor\"]')");
+ waitForGone($page, '@idea-editor');
waitForCreateIdeaEditorTestId($page, "idea-card-{$idea->id}", 'After');
$page->assertSeeIn("@idea-card-{$idea->id}", 'After')
@@ -686,18 +643,18 @@ test('opening and closing an idea in the gallery keeps the loaded pages', functi
$this->actingAs($user);
$page = visit(route('app.create.ideas.index', ['view' => 'gallery']));
- waitForCreateIdeaEditorTestId($page, "idea-card-{$ideas->first()->id}");
+ waitFor($page, "@idea-card-{$ideas->first()->id}");
$page->script("document.querySelector('[data-testid=\"ideas-gallery\"]').scrollTo(0, 1e6)");
- waitForCreateIdeaEditorCondition($page, "document.querySelectorAll('[data-testid^=\"idea-card-menu-\"]').length > {$size}");
+ waitForCount($page, '[data-testid^="idea-card-menu-"]', $size, '>');
expect($page->script("document.querySelectorAll('[data-testid^=\"idea-card-menu-\"]').length"))->toBe($size + 5);
$last = $ideas->last();
$page->script("document.querySelector('[data-testid=\"idea-card-{$last->id}\"]').click()");
- waitForCreateIdeaEditorDialog($page);
+ waitForOpen($page, '@idea-editor');
$page->assertValue('@idea-editor-title', $last->title)
->click('@idea-editor-cancel');
- waitForCreateIdeaEditorCondition($page, "!document.querySelector('[data-testid=\"idea-editor\"]')");
+ waitForGone($page, '@idea-editor');
expect($page->script("document.querySelectorAll('[data-testid^=\"idea-card-menu-\"]').length"))->toBe($size + 5);
$page->assertNoJavaScriptErrors();
@@ -708,18 +665,18 @@ test('editing an idea image swaps in the edited file and releases the original o
$this->actingAs($user);
$page = visit(route('app.create.ideas.create'));
- waitForCreateIdeaEditorDialog($page);
- waitForCreateIdeaEditorTestId($page, 'idea-dropzone');
+ waitForOpen($page, '@idea-editor');
+ waitFor($page, '@idea-dropzone');
$page->fill('@idea-editor-title', 'Edited picture');
selectCreateIdeaEditorFile($page, 'idea-photo.png');
- waitForCreateIdeaEditorTestId($page, 'idea-media-item');
+ waitFor($page, '@idea-media-item');
$page->click('@idea-editor-save');
- waitForCreateIdeaEditorDatabase($page, fn (): bool => Idea::where('title', 'Edited picture')->exists());
+ waitForDatabase($page, fn (): bool => Idea::where('title', 'Edited picture')->exists());
$idea = Idea::where('title', 'Edited picture')->sole();
$original = $idea->ownedMedia()->sole();
$page = visit(route('app.create.ideas.show', $idea));
- waitForCreateIdeaEditorDialog($page);
+ waitForOpen($page, '@idea-editor');
$fixture = base64_encode((string) file_get_contents(base_path('tests/fixtures/crop-quadrants.png')));
$page->script(<<<JS
(() => {
@@ -732,18 +689,19 @@ test('editing an idea image swaps in the edited file and releases the original o
});
})();
JS);
- waitForCreateIdeaEditorTestId($page, 'idea-edit-0');
+ waitFor($page, '@idea-edit-0');
$page->assertMissing('@idea-alt-0')
->assertMissing('@idea-tag-0')
->click('@idea-edit-0');
- waitForCreateIdeaEditorCondition($page, "document.querySelector('[data-testid=\"media-editor-selection\"]')?.getBoundingClientRect().width > 0");
+ waitForState($page, '@media-editor-selection', 'element.getBoundingClientRect().width > 0');
$page->assertMissing('@media-editor-segments')
->click('@media-editor-rotate-right')
->click('@media-editor-apply');
- waitForCreateIdeaEditorCondition($page, "!document.querySelector('[data-testid=\"media-editor\"]') && document.querySelector('[data-testid=\"idea-editor-save\"]')?.disabled === false");
+ waitForGone($page, '@media-editor');
+ waitForState($page, '@idea-editor-save', 'element.disabled === false');
$page->click('@idea-editor-save');
- waitForCreateIdeaEditorDatabase($page, fn (): bool => data_get($idea->refresh()->media, '0.id') !== $original->id);
+ waitForDatabase($page, fn (): bool => data_get($idea->refresh()->media, '0.id') !== $original->id);
$owned = $idea->refresh()->ownedMedia()->sole();
expect($owned->id)->not->toBe($original->id)
@@ -760,11 +718,11 @@ test('the assistant buttons only open the AI sidebar; it closes from its X', fun
$this->actingAs($user);
$page = visit(route('app.create.ideas.show', $idea));
- waitForCreateIdeaEditorDialog($page);
+ waitForOpen($page, '@idea-editor');
foreach (['idea-editor-ai', 'idea-editor-use-assistant'] as $button) {
$page->click("@{$button}");
- waitForCreateIdeaEditorTestId($page, 'idea-editor-assistant');
+ waitFor($page, '@idea-editor-assistant');
$page->assertAttribute("@{$button}", 'aria-pressed', 'true')
->click("@{$button}");
$page->script('new Promise((resolve) => setTimeout(resolve, 300))');
@@ -785,7 +743,7 @@ test('the assistant buttons only open the AI sidebar; it closes from its X', fun
JS))->toBe(['onTheLeft' => true, 'closesApart' => true]);
$page->click('@idea-editor-assistant-close');
- waitForCreateIdeaEditorCondition($page, '!document.querySelector(\'[data-testid="idea-editor-assistant"]\')');
+ waitForGone($page, '@idea-editor-assistant');
$page->assertMissing('@idea-editor-assistant')
->assertAttribute("@{$button}", 'aria-pressed', 'false');
@@ -800,7 +758,7 @@ test('on a phone the title and close share the first row and the stage and label
$this->actingAs($user->fresh());
$page = visit(route('app.create.ideas.create'))->resize(390, 844);
- waitForCreateIdeaEditorDialog($page);
+ waitForOpen($page, '@idea-editor');
expect($page->script(<<<'JS'
(() => {
@@ -840,10 +798,10 @@ test('the generate ideas dialog keeps its footer on screen at 390px in the form
JS;
$page = visit(route('app.create.ideas.index'))->resize(390, 844);
- waitForCreateIdeaEditorTestId($page, 'ideas-generate');
+ waitFor($page, '@ideas-generate');
$page->click('@ideas-generate');
- waitForCreateIdeaEditorTestId($page, 'ideas-generate-dialog');
- waitForCreateIdeaEditorTestId($page, 'ideas-generate-submit');
+ waitFor($page, '@ideas-generate-dialog');
+ waitFor($page, '@ideas-generate-submit');
expect($page->script("document.querySelector('[data-testid=\"ideas-generate-dialog\"]').getAttribute('role') === 'dialog' && document.querySelector('[data-testid=\"ideas-generate-cancel\"]').compareDocumentPosition(document.querySelector('[data-testid=\"ideas-generate-submit\"]')) & Node.DOCUMENT_POSITION_FOLLOWING ? true : false"))->toBeTrue();
@@ -866,11 +824,11 @@ test('the stage picker search ignores accents and matches each word in any order
$this->actingAs($user);
$page = visit(route('app.create.ideas.create'));
- waitForCreateIdeaEditorDialog($page);
+ waitForOpen($page, '@idea-editor');
$page->click('@idea-editor-stage');
- waitForCreateIdeaEditorTestId($page, 'idea-editor-stage-search');
+ waitFor($page, '@idea-editor-stage-search');
$page->type('@idea-editor-stage-search', 'FINAL revisao');
- waitForCreateIdeaEditorTestId($page, "idea-editor-stage-option-{$stage->id}");
+ waitFor($page, "@idea-editor-stage-option-{$stage->id}");
$page->assertPresent("@idea-editor-stage-option-{$stage->id}")
->assertMissing("@idea-editor-stage-option-{$other->id}")
diff --git a/tests/Browser/CreateIdeasBoardTest.php b/tests/Browser/CreateIdeasBoardTest.php
index 96cf06c29..fd4fbb24a 100644
--- a/tests/Browser/CreateIdeasBoardTest.php
+++ b/tests/Browser/CreateIdeasBoardTest.php
@@ -192,7 +192,7 @@ test('deleting a stage keeps its ideas under unassigned', function () {
waitFor($page, '@confirm-delete-action');
$page->assertMissing('@confirm-delete-input')
->click('@confirm-delete-action');
- waitForCondition($page, "!document.querySelector('[data-testid=\"idea-column-{$stages['todo']->id}\"]')");
+ waitForGone($page, "@idea-column-{$stages['todo']->id}");
$page->assertMissing("@idea-column-{$stages['todo']->id}");
expect($page->script("!!document.querySelector('[data-testid=\"idea-column-unassigned\"] [data-testid=\"idea-card-{$a->id}\"]')"))->toBeTrue()
@@ -238,7 +238,7 @@ test('selected ideas are deleted in bulk and the selection can be cleared', func
expect(Idea::whereKey([$a->id, $b->id])->exists())->toBeFalse()
->and(Idea::whereKey($c->id)->exists())->toBeTrue();
- waitForCondition($page, "!document.querySelector('[data-testid=\"ideas-bulk-bar\"]')");
+ waitForGone($page, '@ideas-bulk-bar');
$page->assertMissing('@ideas-bulk-bar');
$page->click("@idea-card-menu-{$c->id}");
@@ -246,7 +246,7 @@ test('selected ideas are deleted in bulk and the selection can be cleared', func
$page->click("@idea-select-{$c->id}");
waitFor($page, '@ideas-clear-selection');
$page->click('@ideas-clear-selection');
- waitForCondition($page, "!document.querySelector('[data-testid=\"ideas-bulk-bar\"]')");
+ waitForGone($page, '@ideas-bulk-bar');
$page->assertMissing('@ideas-bulk-bar')
->assertMissing("@idea-card-checkbox-{$c->id}")
@@ -275,7 +275,7 @@ test('the gallery view lists ideas and filters them by label and stage', functio
$page->click('@ideas-filter-labels-filter');
waitFor($page, "@ideas-filter-labels-option-{$label->id}");
$page->click("@ideas-filter-labels-option-{$label->id}");
- waitForCondition($page, "!document.querySelector('[data-testid=\"idea-card-{$loose->id}\"]')");
+ waitForGone($page, "@idea-card-{$loose->id}");
$page->assertVisible("@idea-card-{$tagged->id}")
->assertMissing("@idea-card-{$loose->id}")
@@ -285,7 +285,7 @@ test('the gallery view lists ideas and filters them by label and stage', functio
waitFor($page, "@idea-card-{$loose->id}");
$page->click('@ideas-filter-labels-untagged-checkbox');
- waitForCondition($page, "!document.querySelector('[data-testid=\"idea-card-{$tagged->id}\"]')");
+ waitForGone($page, "@idea-card-{$tagged->id}");
$page->assertVisible("@idea-card-{$loose->id}")
->assertMissing("@idea-card-{$tagged->id}");
expect($page->script('location.search'))->toContain('untagged=1');
@@ -295,12 +295,12 @@ test('the gallery view lists ideas and filters them by label and stage', functio
$page->assertVisible("@idea-card-{$loose->id}")
->assertPresent('@ideas-filter-labels-settings');
$page->keys('@ideas-filter-labels-search', 'Escape');
- waitForCondition($page, "!document.querySelector('[data-testid=\"ideas-filter-labels-search\"]')");
+ waitForGone($page, '@ideas-filter-labels-search');
$page->click('@ideas-filter-stages-filter');
waitFor($page, "@ideas-filter-stages-option-{$stages['done']->id}");
$page->assertScript("document.querySelector('[data-testid=\"ideas-filter-stages-option-{$stages['done']->id}\"]').getBoundingClientRect().height <= 32", true);
$page->click("@ideas-filter-stages-option-{$stages['done']->id}");
- waitForCondition($page, "!document.querySelector('[data-testid=\"idea-card-{$loose->id}\"]')");
+ waitForGone($page, "@idea-card-{$loose->id}");
$page->assertVisible("@idea-card-{$inDone->id}")
->assertMissing("@idea-card-{$tagged->id}")
@@ -340,7 +340,7 @@ test('a drop made while a move is in flight is applied after the first move comp
$page->drag("@idea-card-{$a->id}", "@idea-column-{$stages['done']->id}");
waitForCondition($page, 'window.__ideaMoves.length === 1');
$page->drag("@idea-card-{$b->id}", "@idea-column-{$stages['done']->id}");
- waitForCondition($page, "!!document.querySelector('[data-testid=\"idea-column-{$stages['done']->id}\"] [data-idea-id=\"{$b->id}\"]')");
+ waitForState($page, "@idea-column-{$stages['done']->id} [data-idea-id=\"{$b->id}\"]", 'true');
expect($page->script('window.__ideaMoves.length'))->toBe(1)
->and($a->refresh()->idea_stage_id)->toBe($stages['todo']->id)
@@ -377,7 +377,7 @@ test('move to stage works on a filtered board and appends to the end of the stag
expect($a->refresh()->idea_stage_id)->toBe($stages['done']->id)
->and($a->position)->toBeGreaterThan($existing->refresh()->position);
- waitForCondition($page, "!!document.querySelector('[data-testid=\"idea-column-{$stages['done']->id}\"] [data-testid=\"idea-card-{$a->id}\"]')");
+ waitForState($page, "@idea-column-{$stages['done']->id} @idea-card-{$a->id}", 'true');
expect($page->script("!!document.querySelector('[data-testid=\"idea-column-{$stages['done']->id}\"] [data-testid=\"idea-card-{$a->id}\"]')"))->toBeTrue();
$page->assertNoJavaScriptErrors();
});
@@ -399,7 +399,7 @@ test('changing a filter clears the selection', function () {
$page->click('@ideas-filter-labels-filter');
waitFor($page, '@ideas-filter-labels-untagged-checkbox');
$page->click('@ideas-filter-labels-untagged-checkbox');
- waitForCondition($page, "!document.querySelector('[data-testid=\"ideas-bulk-bar\"]')");
+ waitForGone($page, '@ideas-bulk-bar');
$page->assertMissing('@ideas-bulk-bar')
->assertNoJavaScriptErrors();
@@ -469,7 +469,7 @@ test('a lifted placeholder shows where a dragged card lands, in its own column a
expect($c->refresh()->idea_stage_id)->toBe($done)
->and(Idea::where('idea_stage_id', $done)->orderBy('position')->pluck('id')->all())->toBe([$d->id, $c->id]);
- waitForCondition($page, "!document.querySelector('[data-testid=\"idea-card-placeholder\"]')");
+ waitForGone($page, '@idea-card-placeholder');
expect(createIdeasBoardCardSlots($page, $done))->toBe([$d->id, $c->id]);
$page->assertNoJavaScriptErrors();
});
@@ -532,7 +532,7 @@ test('a dragged stage leaves a column-sized placeholder where it will land', fun
waitForDatabase($page, fn (): bool => $stages['done']->refresh()->position < $stages['todo']->refresh()->position);
expect($stages['done']->refresh()->position)->toBeLessThan($stages['todo']->refresh()->position);
- waitForCondition($page, "!document.querySelector('[data-testid=\"idea-stage-placeholder\"]')");
+ waitForGone($page, '@idea-stage-placeholder');
expect(createIdeasBoardStageSlots($page))->toBe([$done, $todo, $progress]);
$page->assertNoJavaScriptErrors();
});
@@ -553,7 +553,7 @@ test('the gallery stage filter has an unassigned option that combines with stage
->and($page->script("document.querySelector('[data-testid=\"ideas-filter-stages-unassigned\"]').getBoundingClientRect().height"))->toBeLessThanOrEqual(32);
$page->click('@ideas-filter-stages-unassigned-checkbox');
- waitForCondition($page, "!document.querySelector('[data-testid=\"idea-card-{$inTodo->id}\"]')");
+ waitForGone($page, "@idea-card-{$inTodo->id}");
$page->assertVisible("@idea-card-{$loose->id}")
->assertMissing("@idea-card-{$inDone->id}")
@@ -665,7 +665,7 @@ test('on a phone the label filter shows only its icon and the page does not scro
JS))->toBe(['visibleText' => 0, 'label' => true, 'overflow' => 0, 'boardScrolls' => true]);
$page->resize(1280, 900);
- waitForCondition($page, "[...document.querySelector('[data-testid=\"ideas-filter-labels-filter\"]').querySelectorAll('span')].some((span) => span.offsetParent !== null && span.textContent.trim() !== '')");
+ waitForState($page, '@ideas-filter-labels-filter', "[...element.querySelectorAll('span')].some((span) => span.offsetParent !== null && span.textContent.trim() !== '')");
expect($page->script("[...document.querySelector('[data-testid=\"ideas-filter-labels-filter\"]').querySelectorAll('span')].some((span) => span.offsetParent !== null && span.textContent.trim() !== '')"))->toBeTrue();
$page->assertNoJavaScriptErrors();
});
@@ -683,7 +683,7 @@ test('scrolling a column loads its next ten ideas and the count comes from the d
$page->assertSeeIn("@idea-column-count-{$column}", '15');
$page->script("document.querySelector('[data-testid=\"idea-column-scroll-{$column}\"]').scrollTop = 100000");
- waitForCondition($page, "document.querySelectorAll('[data-testid=\"idea-column-list-{$column}\"] [data-sortable-idea]').length === 15");
+ waitForCount($page, "@idea-column-list-{$column} [data-sortable-idea]", 15);
expect(createIdeasBoardCardSlots($page, $column))->toBe($ideas->pluck('id')->all());
$page->assertSeeIn("@idea-column-count-{$column}", '15')
@@ -708,7 +708,7 @@ test('dragging a card into a partly loaded column keeps the unloaded ideas in or
->and($order->pluck('id')->reject(fn (string $id): bool => $id === $moving->id)->values()->all())->toBe($done->pluck('id')->all())
->and(array_slice($order->pluck('id')->all(), 0, count($shown)))->toBe($shown)
->and($shown)->toContain($moving->id);
- waitForCondition($page, "document.querySelector('[data-testid=\"idea-column-count-{$stages['done']->id}\"]').textContent.trim() === '13'");
+ waitForState($page, "@idea-column-count-{$stages['done']->id}", "element.textContent.trim() === '13'");
$page->assertSeeIn("@idea-column-count-{$stages['done']->id}", '13')
->assertNoJavaScriptErrors();
});
@@ -723,7 +723,7 @@ test('the gallery stage filter search ignores accents and matches each word in a
$page->click('@ideas-filter-stages-filter');
waitFor($page, '@ideas-filter-stages-search');
$page->type('@ideas-filter-stages-search', 'FINAL revisao');
- waitForCondition($page, "!document.querySelector('[data-testid=\"ideas-filter-stages-option-{$stages['todo']->id}\"]')");
+ waitForGone($page, "@ideas-filter-stages-option-{$stages['todo']->id}");
$page->assertPresent("@ideas-filter-stages-option-{$stages['in_progress']->id}")
->assertMissing("@ideas-filter-stages-option-{$stages['todo']->id}")
diff --git a/tests/Browser/CreateShellTest.php b/tests/Browser/CreateShellTest.php
index b6a8a711e..7ee736866 100644
--- a/tests/Browser/CreateShellTest.php
+++ b/tests/Browser/CreateShellTest.php
@@ -6,31 +6,9 @@ use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
-function waitForCreateShellTestId(mixed $page, string $testId): void
-{
- $page->script(<<<JS
- (async () => {
- const sel = '[data-testid="{$testId}"]';
- for (let i = 0; i < 100; i++) {
- const el = document.querySelector(sel);
- if (el && el.getBoundingClientRect().height > 0) return;
- await new Promise((r) => setTimeout(r, 50));
- }
- })();
- JS);
-}
-
function waitForCreateShellMenuSettled(mixed $page): void
{
- $page->script(<<<'JS'
- (async () => {
- for (let i = 0; i < 100; i++) {
- const menu = document.querySelector('[data-testid="sidebar-new-menu"]');
- if (menu && menu.getAnimations({ subtree: true }).every((animation) => animation.playState !== 'running')) return;
- await new Promise((r) => setTimeout(r, 50));
- }
- })();
- JS);
+ waitForState($page, '@sidebar-new-menu', "element.getAnimations({ subtree: true }).every((animation) => animation.playState !== 'running')");
}
function createShellUser(): User
@@ -52,9 +30,9 @@ test('the new menu lists its items in order for an admin and each one opens its
$this->actingAs(createShellUser());
$page = visit(route('app.create.ideas.index'));
- waitForCreateShellTestId($page, 'sidebar-new');
+ waitFor($page, '@sidebar-new');
$page->click('@sidebar-new');
- waitForCreateShellTestId($page, 'sidebar-new-member');
+ waitFor($page, '@sidebar-new-member');
waitForCreateShellMenuSettled($page);
expect($page->script('[...document.querySelectorAll(\'[data-testid^="sidebar-new-"]:not([data-testid="sidebar-new-menu"]):not([data-testid$="-icon"])\')].map((el) => el.dataset.testid)'))
@@ -62,40 +40,26 @@ test('the new menu lists its items in order for an admin and each one opens its
expect($page->script("document.querySelector('[data-testid=\"sidebar-new-menu\"]').getBoundingClientRect().top >= document.querySelector('[data-testid=\"sidebar-new\"]').getBoundingClientRect().bottom"))->toBeTrue();
$page->click('@sidebar-new-channel');
- waitForCreateShellTestId($page, 'connect-channel-dialog');
+ waitFor($page, '@connect-channel-dialog');
$page->assertVisible('@connect-channel-dialog')
->keys('@connect-channel-dialog', 'Escape');
- $page->script(<<<'JS'
- (async () => {
- for (let i = 0; i < 100; i++) {
- if (!document.querySelector('[data-testid="connect-channel-dialog"]')) return;
- await new Promise((r) => setTimeout(r, 50));
- }
- })();
- JS);
+ waitForGone($page, '@connect-channel-dialog');
$page->click('@sidebar-new');
- waitForCreateShellTestId($page, 'sidebar-new-member');
+ waitFor($page, '@sidebar-new-member');
waitForCreateShellMenuSettled($page);
$page->click('@sidebar-new-member');
- waitForCreateShellTestId($page, 'invite-member-dialog');
+ waitFor($page, '@invite-member-dialog');
$page->assertVisible('@invite-member-dialog')
->assertVisible('#invite-email')
->click('@invite-member-cancel');
- $page->script(<<<'JS'
- (async () => {
- for (let i = 0; i < 100; i++) {
- if (!document.querySelector('[data-testid="invite-member-dialog"]')) return;
- await new Promise((r) => setTimeout(r, 50));
- }
- })();
- JS);
+ waitForGone($page, '@invite-member-dialog');
$page->click('@sidebar-new');
- waitForCreateShellTestId($page, 'sidebar-new-idea');
+ waitFor($page, '@sidebar-new-idea');
waitForCreateShellMenuSettled($page);
$page->click('@sidebar-new-idea');
- waitForCreateShellTestId($page, 'create-header');
+ waitFor($page, '@create-header');
$page->assertVisible('@create-header')
->assertScript('location.pathname', parse_url(route('app.create.ideas.create'), PHP_URL_PATH))
@@ -106,11 +70,11 @@ test('the new menu opens the post composer', function () {
$this->actingAs(createShellUser());
$page = visit(route('app.create.ideas.index'));
- waitForCreateShellTestId($page, 'sidebar-new');
+ waitFor($page, '@sidebar-new');
$page->click('@sidebar-new');
- waitForCreateShellTestId($page, 'sidebar-new-post');
+ waitFor($page, '@sidebar-new-post');
$page->click('@sidebar-new-post');
- waitForCreateShellTestId($page, 'post-composer-dialog');
+ waitFor($page, '@post-composer-dialog');
$page->assertVisible('@post-composer-dialog')->assertNoJavaScriptErrors();
});
@@ -120,8 +84,8 @@ test('the create nav item links to ideas and the ideas tab is current', function
$page = visit(route('app.create.ideas.index'));
$href = parse_url(route('app.create.ideas.index'), PHP_URL_PATH);
- waitForCreateShellTestId($page, "nav-{$href}");
- waitForCreateShellTestId($page, 'create-tab-ideas');
+ waitFor($page, "[data-testid=\"nav-{$href}\"]");
+ waitFor($page, '@create-tab-ideas');
$page->assertVisible("@nav-{$href}")
->assertScript("document.querySelector('[data-testid=\"nav-{$href}\"]').getAttribute('href')", $href)
@@ -139,9 +103,9 @@ test('the new menu hides connect channel and invite member from a member', funct
$this->actingAs($member->fresh());
$page = visit(route('app.create.ideas.index'));
- waitForCreateShellTestId($page, 'sidebar-new');
+ waitFor($page, '@sidebar-new');
$page->click('@sidebar-new');
- waitForCreateShellTestId($page, 'sidebar-new-idea');
+ waitFor($page, '@sidebar-new-idea');
$page->assertVisible('@sidebar-new-post')
->assertMissing('@sidebar-new-channel')
@@ -153,7 +117,7 @@ test('the create tabs border keeps the same padding as the publish page', functi
$this->actingAs(createShellUser());
$page = visit(route('app.create.ideas.index'))->resize(1440, 900);
- waitForCreateShellTestId($page, 'create-tabs');
+ waitFor($page, '@create-tabs');
$edges = $page->script(<<<'JS'
(() => {
diff --git a/tests/Browser/CreateTemplatesTest.php b/tests/Browser/CreateTemplatesTest.php
index a0af540c0..89185f47f 100644
--- a/tests/Browser/CreateTemplatesTest.php
+++ b/tests/Browser/CreateTemplatesTest.php
@@ -7,54 +7,6 @@ use App\Models\PostTemplate;
use App\Models\User;
use App\Models\Workspace;
-function waitForCreateTemplatesTestId(mixed $page, string $testId): void
-{
- $page->script(<<<JS
- (async () => {
- for (let attempt = 0; attempt < 200; attempt++) {
- if (document.querySelector('[data-testid="{$testId}"]')?.getBoundingClientRect().height > 0) return;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })();
- JS);
-}
-
-function waitForCreateTemplatesCondition(mixed $page, string $condition): void
-{
- $page->script(<<<JS
- (async () => {
- for (let attempt = 0; attempt < 200; attempt++) {
- if ({$condition}) return;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })();
- JS);
-}
-
-/**
- * Dialogs animate in; a click that lands before the animation settles is swallowed.
- */
-function waitForCreateTemplatesDialog(mixed $page, string $testId): void
-{
- $page->script(<<<JS
- (async () => {
- for (let attempt = 0; attempt < 200; attempt++) {
- const dialog = document.querySelector('[data-testid="{$testId}"]');
- if (dialog?.getAttribute('data-state') === 'open'
- && dialog.getAnimations().every((animation) => animation.playState !== 'running')) return;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })();
- JS);
-}
-
-function waitForCreateTemplatesDatabase(mixed $page, Closure $condition): void
-{
- for ($attempt = 0; $attempt < 50 && ! $condition(); $attempt++) {
- $page->script('new Promise((resolve) => setTimeout(resolve, 100))');
- }
-}
-
function createTemplatesCardCount(mixed $page, string $scopeTestId): int
{
return $page->script("document.querySelectorAll('[data-testid=\"{$scopeTestId}\"] article[data-testid^=\"template-card-\"]').length");
@@ -82,7 +34,7 @@ test('discover shows the featured band, capped rows and the scope counts', funct
$this->actingAs($user);
$page = visit(route('app.create.templates.index'));
- waitForCreateTemplatesTestId($page, 'templates-featured');
+ waitFor($page, '@templates-featured');
$page->assertVisible('@create-tab-templates')
->assertAttribute('@create-tab-templates', 'aria-current', 'page')
@@ -101,7 +53,7 @@ test('the filter narrows the library, updates the url and resets', function () {
$this->actingAs($user);
$page = visit(route('app.create.templates.index'));
- waitForCreateTemplatesTestId($page, 'templates-filter');
+ waitFor($page, '@templates-filter');
$page->script(<<<'JS'
(() => {
window.__sawEmptyState = false;
@@ -111,9 +63,9 @@ test('the filter narrows the library, updates the url and resets', function () {
})()
JS);
$page->click('@templates-filter');
- waitForCreateTemplatesTestId($page, 'templates-filter-type-question');
+ waitFor($page, '@templates-filter-type-question');
$page->click('@templates-filter-type-question');
- waitForCreateTemplatesTestId($page, 'templates-results');
+ waitFor($page, '@templates-results');
expect($page->script('window.__sawEmptyState'))->toBeFalse();
@@ -121,7 +73,7 @@ test('the filter narrows the library, updates the url and resets', function () {
->and(urldecode($page->script('window.location.search')))->toMatch('/types\[\d*\]=question/');
$page->click('@templates-filter-reset');
- waitForCreateTemplatesTestId($page, 'templates-featured');
+ waitFor($page, '@templates-featured');
$page->assertVisible('@templates-row-story')->assertNoJavaScriptErrors();
});
@@ -131,14 +83,14 @@ test('a library card opens its detail in place and use template opens the compos
$this->actingAs($user);
$page = visit(route('app.create.templates.index'));
- waitForCreateTemplatesTestId($page, 'template-card-origin_story');
+ waitFor($page, '@template-card-origin_story');
$page->click('@template-card-origin_story');
- waitForCreateTemplatesDialog($page, 'template-detail');
+ waitForOpen($page, '@template-detail');
expect($page->script('window.location.pathname + window.location.search'))->toBe(route('app.create.templates.index', [], false));
$page->click('@template-use');
- waitForCreateTemplatesTestId($page, 'composer-base-content');
+ waitFor($page, '@composer-base-content');
$body = __('template_library.origin_story.body');
$page->assertVisible('@post-composer-dialog')
@@ -152,15 +104,15 @@ test('creating a personal template shows the card without a success toast', func
$this->actingAs($user);
$page = visit(route('app.create.templates.index'));
- waitForCreateTemplatesTestId($page, 'templates-scope-personal');
+ waitFor($page, '@templates-scope-personal');
$page->click('@templates-scope-personal');
- waitForCreateTemplatesTestId($page, 'templates-empty');
+ waitFor($page, '@templates-empty');
$page->click('@templates-new');
- waitForCreateTemplatesDialog($page, 'template-editor');
+ waitForOpen($page, '@template-editor');
$page->fill('@template-editor-title', 'Weekly recap')
->fill('@template-editor-body', "• Win\n• Lesson");
$page->click('@template-editor-save');
- waitForCreateTemplatesCondition($page, "document.querySelectorAll('article[data-testid^=\"template-card-\"]').length === 1");
+ waitForCount($page, 'article[data-testid^="template-card-"]', 1);
$page->assertSeeIn('@templates-grid', 'Weekly recap')
->assertSeeIn('@templates-scope-count-personal', '1')
@@ -177,17 +129,17 @@ test('duplicating a library template into the team scope adds the copy suffix',
$this->actingAs($user);
$page = visit(route('app.create.templates.index'));
- waitForCreateTemplatesTestId($page, 'template-card-quick_win');
+ waitFor($page, '@template-card-quick_win');
$page->click('@template-card-menu-quick_win');
- waitForCreateTemplatesTestId($page, 'template-duplicate-quick_win');
+ waitFor($page, '@template-duplicate-quick_win');
$page->click('@template-duplicate-quick_win');
- waitForCreateTemplatesDialog($page, 'template-duplicate-dialog');
+ waitForOpen($page, '@template-duplicate-dialog');
$page->assertSeeIn('@template-duplicate-dialog', __('template_library.quick_win.title'))
->click('@template-duplicate-visibility');
- waitForCreateTemplatesTestId($page, 'template-duplicate-visibility-team');
+ waitFor($page, '@template-duplicate-visibility-team');
$page->click('@template-duplicate-visibility-team');
$page->click('@template-duplicate-confirm');
- waitForCreateTemplatesCondition($page, "document.querySelectorAll('[data-testid=\"templates-grid\"] article').length === 1");
+ waitForCount($page, '@templates-grid article', 1);
$page->assertSeeIn('@templates-grid', __('template_library.quick_win.title').' (copy)')
->assertSeeIn('@templates-scope-count-team', '1')
@@ -207,16 +159,16 @@ test('deleting a template asks for confirmation without typing a keyword', funct
$this->actingAs($user);
$page = visit(route('app.create.templates.index', ['view' => 'team']));
- waitForCreateTemplatesTestId($page, "template-card-{$template->id}");
+ waitFor($page, "@template-card-{$template->id}");
$page->click("@template-card-menu-{$template->id}");
- waitForCreateTemplatesTestId($page, "template-delete-{$template->id}");
+ waitFor($page, "@template-delete-{$template->id}");
$page->click("@template-delete-{$template->id}");
- waitForCreateTemplatesDialog($page, 'confirm-delete-modal');
+ waitForOpen($page, '@confirm-delete-modal');
$page->assertMissing('@confirm-delete-input')
->click('@template-delete-confirm');
- waitForCreateTemplatesDatabase($page, fn () => PostTemplate::query()->whereKey($template->id)->doesntExist());
- waitForCreateTemplatesCondition($page, "!document.querySelector('[data-testid=\"template-card-{$template->id}\"]')");
+ waitForDatabase($page, fn () => PostTemplate::query()->whereKey($template->id)->doesntExist());
+ waitForGone($page, "@template-card-{$template->id}");
expect(PostTemplate::query()->whereKey($template->id)->exists())->toBeFalse();
$page->assertMissing("@template-card-{$template->id}")->assertNoJavaScriptErrors();
@@ -228,11 +180,11 @@ test('editing a template from its menu updates the card and the row', function (
$this->actingAs($user);
$page = visit(route('app.create.templates.index', ['view' => 'personal']));
- waitForCreateTemplatesTestId($page, "template-card-{$template->id}");
+ waitFor($page, "@template-card-{$template->id}");
$page->click("@template-card-menu-{$template->id}");
- waitForCreateTemplatesTestId($page, "template-edit-{$template->id}");
+ waitFor($page, "@template-edit-{$template->id}");
$page->click("@template-edit-{$template->id}");
- waitForCreateTemplatesDialog($page, 'template-editor');
+ waitForOpen($page, '@template-editor');
expect($page->script('window.location.pathname + window.location.search'))->toBe(route('app.create.templates.index', ['view' => 'personal'], false));
@@ -240,7 +192,7 @@ test('editing a template from its menu updates the card and the row', function (
->fill('@template-editor-title', 'Final title')
->fill('@template-editor-body', 'New body')
->click('@template-editor-save');
- waitForCreateTemplatesCondition($page, "(document.querySelector('[data-testid=\"templates-grid\"]')?.textContent ?? '').includes('Final title')");
+ waitForText($page, '@templates-grid', 'Final title');
$template->refresh();
@@ -259,7 +211,7 @@ test('a picked emoji is kept among the user\'s recents in this browser', functio
$page = visit(route('app.create.templates.index'));
waitFor($page, '@templates-new');
$page->click('@templates-new');
- waitForState($page, '@template-editor', "element.getAttribute('data-state') === 'open' && element.getAnimations().every((animation) => animation.playState !== 'running')");
+ waitForOpen($page, '@template-editor');
$page->click('@template-editor-emoji');
waitFor($page, '@emoji-picker-option');
$emoji = $page->script(<<<'JS'
@@ -276,7 +228,7 @@ test('a picked emoji is kept among the user\'s recents in this browser', functio
$page->navigate(route('app.create.templates.index'));
waitFor($page, '@templates-new');
$page->click('@templates-new');
- waitForState($page, '@template-editor', "element.getAttribute('data-state') === 'open' && element.getAnimations().every((animation) => animation.playState !== 'running')");
+ waitForOpen($page, '@template-editor');
$page->click('@template-editor-emoji');
waitFor($page, '@emoji-picker-recent');
@@ -290,12 +242,12 @@ test('the emoji picker sets the template emoji', function () {
$this->actingAs($user);
$page = visit(route('app.create.templates.index'));
- waitForCreateTemplatesTestId($page, 'templates-new');
+ waitFor($page, '@templates-new');
$page->click('@templates-new');
- waitForCreateTemplatesDialog($page, 'template-editor');
+ waitForOpen($page, '@template-editor');
$page->assertSeeIn('@template-editor-emoji', '📝')
->click('@template-editor-emoji');
- waitForCreateTemplatesTestId($page, 'emoji-picker-option');
+ waitFor($page, '@emoji-picker-option');
$gap = $page->script(<<<'JS'
(async () => {
@@ -331,12 +283,12 @@ test('the emoji picker sets the template emoji', function () {
})()
JS);
- waitForCreateTemplatesCondition($page, '!document.querySelector(\'[data-testid="emoji-picker-option"]\')');
+ waitForGone($page, '@emoji-picker-option');
$page->assertSeeIn('@template-editor-emoji', $emoji)
->fill('@template-editor-title', 'With emoji')
->fill('@template-editor-body', 'Body')
->click('@template-editor-save');
- waitForCreateTemplatesDatabase($page, fn () => PostTemplate::query()->where('workspace_id', $workspace->id)->exists());
+ waitForDatabase($page, fn () => PostTemplate::query()->where('workspace_id', $workspace->id)->exists());
expect($emoji)->not->toBe('📝')
->and(PostTemplate::query()->where('workspace_id', $workspace->id)->sole()->emoji)->toBe($emoji);
@@ -348,19 +300,19 @@ test('a card opens with Enter and Space from its own button', function () {
$this->actingAs($user);
$page = visit(route('app.create.templates.index'));
- waitForCreateTemplatesTestId($page, 'template-card-open-origin_story');
+ waitFor($page, '@template-card-open-origin_story');
expect($page->script("document.querySelector('[data-testid=\"template-card-origin_story\"]').hasAttribute('role')"))->toBeFalse();
$page->keys('@template-card-open-origin_story', 'Enter');
- waitForCreateTemplatesDialog($page, 'template-detail');
+ waitForOpen($page, '@template-detail');
$page->assertVisible('@template-detail')
->keys('@template-detail', 'Escape');
- waitForCreateTemplatesCondition($page, "!document.querySelector('[data-testid=\"template-detail\"]')");
+ waitForGone($page, '@template-detail');
$page->assertMissing('@template-detail')
->keys('@template-card-open-origin_story', 'Space');
- waitForCreateTemplatesDialog($page, 'template-detail');
+ waitForOpen($page, '@template-detail');
$page->assertVisible('@template-detail')->assertNoJavaScriptErrors();
});
@@ -374,11 +326,11 @@ test('only the creator can change the visibility of a team template', function (
$this->actingAs($bob->fresh());
$page = visit(route('app.create.templates.index', ['view' => 'team']));
- waitForCreateTemplatesTestId($page, "template-card-menu-{$template->id}");
+ waitFor($page, "@template-card-menu-{$template->id}");
$page->click("@template-card-menu-{$template->id}");
- waitForCreateTemplatesTestId($page, "template-edit-{$template->id}");
+ waitFor($page, "@template-edit-{$template->id}");
$page->click("@template-edit-{$template->id}");
- waitForCreateTemplatesDialog($page, 'template-editor');
+ waitForOpen($page, '@template-editor');
$page->assertVisible('@template-editor-visibility-hint')
->assertNoJavaScriptErrors();
@@ -391,20 +343,20 @@ test('dialogs put cancel before the primary action', function () {
$this->actingAs($user);
$page = visit(route('app.create.templates.index'));
- waitForCreateTemplatesTestId($page, 'templates-new');
+ waitFor($page, '@templates-new');
$page->click('@templates-new');
- waitForCreateTemplatesDialog($page, 'template-editor');
+ waitForOpen($page, '@template-editor');
$editorOrder = $page->script(<<<'JS'
document.querySelector('[data-testid="template-editor-cancel"]').compareDocumentPosition(document.querySelector('[data-testid="template-editor-save"]')) & Node.DOCUMENT_POSITION_FOLLOWING
JS);
$page->click('@template-editor-cancel');
- waitForCreateTemplatesTestId($page, 'template-card-quick_win');
+ waitFor($page, '@template-card-quick_win');
$page->click('@template-card-menu-quick_win');
- waitForCreateTemplatesTestId($page, 'template-duplicate-quick_win');
+ waitFor($page, '@template-duplicate-quick_win');
$page->click('@template-duplicate-quick_win');
- waitForCreateTemplatesDialog($page, 'template-duplicate-dialog');
+ waitForOpen($page, '@template-duplicate-dialog');
$duplicateOrder = $page->script(<<<'JS'
document.querySelector('[data-testid="template-duplicate-cancel"]').compareDocumentPosition(document.querySelector('[data-testid="template-duplicate-confirm"]')) & Node.DOCUMENT_POSITION_FOLLOWING
@@ -420,7 +372,7 @@ test('a matching discover search keeps the rows until the results arrive', funct
$this->actingAs($user);
$page = visit(route('app.create.templates.index'));
- waitForCreateTemplatesTestId($page, 'templates-search');
+ waitFor($page, '@templates-search');
$page->script(<<<'JS'
(() => {
window.__sawEmptyState = false;
@@ -430,9 +382,9 @@ test('a matching discover search keeps the rows until the results arrive', funct
})()
JS);
$page->click('@templates-search');
- waitForCreateTemplatesTestId($page, 'templates-search-input');
+ waitFor($page, '@templates-search-input');
$page->fill('@templates-search-input', 'five-minute');
- waitForCreateTemplatesTestId($page, 'templates-results');
+ waitFor($page, '@templates-results');
expect($page->script('window.__sawEmptyState'))->toBeFalse()
->and(createTemplatesCardCount($page, 'templates-results'))->toBeGreaterThan(0);
@@ -453,20 +405,20 @@ test('the detail and the editor close with the close button, escape and an outsi
];
foreach ($closers as $close) {
- waitForCreateTemplatesTestId($page, 'template-card-origin_story');
+ waitFor($page, '@template-card-origin_story');
$page->click('@template-card-origin_story');
- waitForCreateTemplatesDialog($page, 'template-detail');
+ waitForOpen($page, '@template-detail');
$close();
- waitForCreateTemplatesCondition($page, "!document.querySelector('[data-testid=\"template-detail\"]')");
+ waitForGone($page, '@template-detail');
$page->assertMissing('@template-detail');
expect($page->script('window.location.pathname + window.location.search'))->toBe($path);
}
$page->click('@templates-new');
- waitForCreateTemplatesDialog($page, 'template-editor');
+ waitForOpen($page, '@template-editor');
$page->keys('@template-editor', 'Escape');
- waitForCreateTemplatesCondition($page, "!document.querySelector('[data-testid=\"template-editor\"]')");
+ waitForGone($page, '@template-editor');
$page->assertMissing('@template-editor')->assertNoJavaScriptErrors();
expect($page->script('window.location.pathname + window.location.search'))->toBe($path);
@@ -477,21 +429,21 @@ test('the visibility select shows a user icon for personal and the channels grid
$this->actingAs($user);
$page = visit(route('app.create.templates.index'));
- waitForCreateTemplatesTestId($page, 'templates-scope-personal');
+ waitFor($page, '@templates-scope-personal');
$page->click('@templates-scope-personal');
- waitForCreateTemplatesTestId($page, 'templates-empty');
+ waitFor($page, '@templates-empty');
$page->click('@templates-new');
- waitForCreateTemplatesDialog($page, 'template-editor');
+ waitForOpen($page, '@template-editor');
$page->assertVisible('@template-editor-visibility-icon-personal');
$page->click('@template-editor-visibility');
- waitForCreateTemplatesTestId($page, 'template-editor-visibility-team');
+ waitFor($page, '@template-editor-visibility-team');
expect($page->script("document.querySelectorAll('[data-testid^=\"template-editor-visibility-\"] svg').length"))->toBeGreaterThanOrEqual(2);
$page->click('@template-editor-visibility-team');
- waitForCreateTemplatesTestId($page, 'template-editor-visibility-icon-team');
+ waitFor($page, '@template-editor-visibility-icon-team');
expect($page->script("document.querySelector('[data-testid=\"template-editor-visibility-icon-team\"]').classList.contains('tabler-icon-layout-grid')"))->toBeTrue();
@@ -507,7 +459,7 @@ test('clicking the active scope again does not duplicate its templates', functio
$this->actingAs($user);
$page = visit(route('app.create.templates.index', ['view' => $scope]));
- waitForCreateTemplatesCondition($page, "document.querySelectorAll('article[data-testid^=\"template-card-\"]').length === 1");
+ waitForCount($page, 'article[data-testid^="template-card-"]', 1);
foreach (range(1, 3) as $attempt) {
$page->click("@templates-scope-{$scope}");
@@ -517,9 +469,9 @@ test('clicking the active scope again does not duplicate its templates', functio
expect($page->script("document.querySelectorAll('article[data-testid^=\"template-card-\"]').length"))->toBe(1);
$page->click('@templates-scope-discover');
- waitForCreateTemplatesTestId($page, 'templates-featured');
+ waitFor($page, '@templates-featured');
$page->click("@templates-scope-{$scope}");
- waitForCreateTemplatesCondition($page, "document.querySelectorAll('article[data-testid^=\"template-card-\"]').length >= 1");
+ waitForCount($page, 'article[data-testid^="template-card-"]', 1, '>=');
$page->script('new Promise((resolve) => setTimeout(resolve, 600))');
expect($page->script("document.querySelectorAll('article[data-testid^=\"template-card-\"]').length"))->toBe(1);
diff --git a/tests/Browser/CreateWorkspaceMetadataSheetTest.php b/tests/Browser/CreateWorkspaceMetadataSheetTest.php
index d31eb5b82..009400ed9 100644
--- a/tests/Browser/CreateWorkspaceMetadataSheetTest.php
+++ b/tests/Browser/CreateWorkspaceMetadataSheetTest.php
@@ -54,14 +54,7 @@ test('workspace metadata creation uses a centered dialog and still saves', funct
}
$page->click("@submit-create-{$resource}");
- $page->script(<<<JS
- (async () => {
- for (let attempt = 0; attempt < 100; attempt++) {
- if (! document.querySelector('[data-testid="create-{$resource}-sheet"]')) return;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })();
- JS);
+ waitForGone($page, "@create-{$resource}-sheet");
$this->assertDatabaseHas($table, [
'workspace_id' => $workspace->id,
diff --git a/tests/Browser/DarkModeSurfacesTest.php b/tests/Browser/DarkModeSurfacesTest.php
index 08f32c666..3cdc3d921 100644
--- a/tests/Browser/DarkModeSurfacesTest.php
+++ b/tests/Browser/DarkModeSurfacesTest.php
@@ -16,26 +16,6 @@ use App\Models\User;
use App\Models\Workspace;
use Illuminate\Support\Facades\Queue;
-function waitForDarkModeSurfacesTestId(mixed $page, string $testId): void
-{
- $page->script(<<<JS
- new Promise((resolve, reject) => {
- const started = Date.now();
- const check = () => {
- const element = document.querySelector('[data-testid="{$testId}"]');
- if (element && element.getBoundingClientRect().height > 0) {
- resolve(true);
- } else if (Date.now() - started > 10000) {
- reject(new Error('Timed out waiting for {$testId}'));
- } else {
- requestAnimationFrame(check);
- }
- };
- check();
- })
- JS);
-}
-
test('in dark mode a dialog is a raised surface, lighter than the page behind it', function () {
$user = User::factory()->create(['theme' => Theme::Dark]);
$workspace = Workspace::factory()->create(['user_id' => $user->id]);
@@ -46,7 +26,7 @@ test('in dark mode a dialog is a raised surface, lighter than the page behind it
$this->actingAs($user);
$page = visit(route('app.posts.edit', $post))->resize(1440, 900);
- waitForDarkModeSurfacesTestId($page, 'post-composer-dialog');
+ waitFor($page, '@post-composer-dialog');
$surfaces = $page->script(<<<'JS'
(() => {
@@ -71,9 +51,9 @@ test('in dark mode the new menu icons stand out from their tiles', function () {
$this->actingAs($user);
$page = visit(route('app.posts.index'))->resize(1440, 900);
- waitForDarkModeSurfacesTestId($page, 'sidebar-new');
+ waitFor($page, '@sidebar-new');
$page->click('@sidebar-new');
- waitForDarkModeSurfacesTestId($page, 'sidebar-new-idea-icon');
+ waitFor($page, '@sidebar-new-idea-icon');
$contrast = $page->script(<<<'JS'
(() => {
@@ -102,9 +82,9 @@ test('in dark mode the new button hovers one step lighter, not to the palest vio
$this->actingAs($user);
$page = visit(route('app.posts.index'))->resize(1440, 900);
- waitForDarkModeSurfacesTestId($page, 'sidebar-new');
+ waitFor($page, '@sidebar-new');
$page->click('@sidebar-new');
- waitForDarkModeSurfacesTestId($page, 'sidebar-new-menu');
+ waitFor($page, '@sidebar-new-menu');
$colors = $page->script(<<<'JS'
new Promise((done) => setTimeout(() => {
@@ -139,7 +119,7 @@ test('in dark mode the idea board columns and cards step up from the page', func
$this->actingAs($user);
$page = visit(route('app.create.ideas.index'))->resize(1440, 900);
- waitForDarkModeSurfacesTestId($page, "idea-card-{$idea->id}");
+ waitFor($page, "@idea-card-{$idea->id}");
$surfaces = $page->script(<<<JS
(() => {
@@ -184,7 +164,7 @@ test('in dark mode each insights section is one card outlined against the page p
$this->actingAs($user);
$page = visit(route('app.insights'))->resize(1440, 900);
- waitForDarkModeSurfacesTestId($page, 'analytics-summary-followers');
+ waitFor($page, '@analytics-summary-followers');
$surfaces = $page->script(<<<'JS'
(() => {
@@ -222,9 +202,9 @@ test('in dark mode the connect channel dialog keeps its 8px frame around the inn
$this->actingAs($user);
$page = visit(route('app.repurposes.index'))->resize(1440, 900);
- waitForDarkModeSurfacesTestId($page, 'repurposes-empty-connect');
+ waitFor($page, '@repurposes-empty-connect');
$page->click('@repurposes-empty-connect');
- waitForDarkModeSurfacesTestId($page, 'connect-channel-telegram');
+ waitFor($page, '@connect-channel-telegram');
$layers = $page->script(<<<'JS'
(() => {
diff --git a/tests/Browser/DialogFooterTest.php b/tests/Browser/DialogFooterTest.php
index 39765310f..352633204 100644
--- a/tests/Browser/DialogFooterTest.php
+++ b/tests/Browser/DialogFooterTest.php
@@ -5,19 +5,6 @@ declare(strict_types=1);
use App\Models\User;
use App\Models\Workspace;
-function waitForDialogFooterTestId(mixed $page, string $testId): void
-{
- $page->script(<<<JS
- (async () => {
- for (let attempt = 0; attempt < 200; attempt++) {
- const element = document.querySelector('[data-testid="{$testId}"]');
- if (element && element.getBoundingClientRect().height > 0) return;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })();
- JS);
-}
-
test('a dialog footer sits in a rounded muted panel inset from the dialog edges', function () {
$user = User::factory()->create();
$workspace = Workspace::factory()->create(['account_id' => $user->account_id, 'user_id' => $user->id]);
@@ -27,9 +14,9 @@ test('a dialog footer sits in a rounded muted panel inset from the dialog edges'
$this->actingAs($user->fresh());
$page = visit(route('app.labels.index'))->resize(1280, 900);
- waitForDialogFooterTestId($page, 'labels-empty-create');
+ waitFor($page, '@labels-empty-create');
$page->click('@labels-empty-create');
- waitForDialogFooterTestId($page, 'create-label-sheet');
+ waitFor($page, '@create-label-sheet');
$page->script('new Promise((resolve) => setTimeout(resolve, 400))');
$footer = $page->script(<<<'JS'
diff --git a/tests/Browser/DialogFullScreenMobileTest.php b/tests/Browser/DialogFullScreenMobileTest.php
index bb8b09f2c..9d9e4cd7a 100644
--- a/tests/Browser/DialogFullScreenMobileTest.php
+++ b/tests/Browser/DialogFullScreenMobileTest.php
@@ -8,16 +8,7 @@ use App\Models\WorkspaceLabel;
function waitForDialogFullScreenTestId(mixed $page, string $testId): void
{
- $page->script(<<<JS
- (async () => {
- for (let attempt = 0; attempt < 200; attempt++) {
- const element = document.querySelector('[data-testid="{$testId}"]');
- if (element && element.getBoundingClientRect().height > 0
- && element.getAnimations().every((animation) => animation.playState !== 'running')) return;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })();
- JS);
+ waitForState($page, "@{$testId}", "element.getBoundingClientRect().height > 0 && element.getAnimations().every((animation) => animation.playState !== 'running')");
}
function dialogFullScreenAdmin(): User
diff --git a/tests/Browser/ImageCropperTest.php b/tests/Browser/ImageCropperTest.php
index 10f3d1e23..d08591af3 100644
--- a/tests/Browser/ImageCropperTest.php
+++ b/tests/Browser/ImageCropperTest.php
@@ -15,13 +15,11 @@ function selectPhoto(mixed $page): void
{
$base64 = base64_encode((string) file_get_contents(base_path('tests/fixtures/crop-quadrants.png')));
+ waitForState($page, 'input[type="file"]', 'true');
+
$page->script(<<<JS
- (async () => {
- const findInput = () => document.querySelector('input[type="file"]');
- for (let attempt = 0; attempt < 50 && !findInput(); attempt++) {
- await new Promise((resolve) => setTimeout(resolve, 100));
- }
- const input = findInput();
+ (() => {
+ const input = document.querySelector('input[type="file"]');
const bytes = Uint8Array.from(atob('{$base64}'), (character) => character.charCodeAt(0));
const file = new File([bytes], 'logo.png', { type: 'image/png' });
const data = new DataTransfer();
@@ -69,27 +67,6 @@ function recordUpload(mixed $page): void
JS);
}
-/**
- * Polls from the page until `$condition` holds (never sleep(): the test server
- * only ticks while Pest awaits Playwright).
- */
-function waitForImageCrop(mixed $page, string $condition): void
-{
- $page->script(<<<JS
- (async () => {
- for (let attempt = 0; attempt < 100; attempt++) {
- if ({$condition}) return;
- await new Promise((resolve) => setTimeout(resolve, 100));
- }
- })();
- JS);
-}
-
-function waitForCropSelection(mixed $page): void
-{
- waitForImageCrop($page, "document.querySelector('[data-testid=\"media-editor-selection\"]')?.getBoundingClientRect().width > 0");
-}
-
/**
* The selection overlay's on-screen size.
*
@@ -182,7 +159,7 @@ test('a profile photo opens the media editor locked to a square 1:1 crop and sav
$page = visit(route('app.profile.edit'));
selectPhoto($page);
- waitForCropSelection($page);
+ waitForState($page, '@media-editor-selection', 'element.getBoundingClientRect().width > 0');
recordUpload($page);
$selection = cropSelectionBox($page);
@@ -206,7 +183,7 @@ test('a profile photo opens the media editor locked to a square 1:1 crop and sav
expect($resized['width'])->toEqualWithDelta($resized['height'], 1);
$page->click('@media-editor-reset');
- waitForImageCrop($page, "document.querySelector('[data-testid=\"media-editor-reset\"]').disabled");
+ waitForState($page, '@media-editor-reset', 'element.disabled');
$page->click('@media-editor-apply')
->assertNoJavaScriptErrors();
@@ -225,7 +202,7 @@ test('a profile photo opens the media editor locked to a square 1:1 crop and sav
->and(isQuadrantColour($request['pixels']['bottomLeft'], [0, 0, 255]))->toBeTrue()
->and(isQuadrantColour($request['pixels']['bottomRight'], [255, 255, 0]))->toBeTrue();
- waitForImageCrop($page, "!document.querySelector('[data-testid=\"media-editor\"]')");
+ waitForGone($page, '@media-editor');
expect($page->script("Boolean(document.querySelector('[data-testid=\"media-editor\"]'))"))->toBeFalse();
});
@@ -236,11 +213,11 @@ test('cancelling the editor discards the photo without uploading', function () {
$page = visit(route('app.profile.edit'));
selectPhoto($page);
- waitForCropSelection($page);
+ waitForState($page, '@media-editor-selection', 'element.getBoundingClientRect().width > 0');
recordUpload($page);
$page->click('@media-editor-cancel');
- waitForImageCrop($page, "!document.querySelector('[data-testid=\"media-editor\"]')");
+ waitForGone($page, '@media-editor');
expect($page->script("Boolean(document.querySelector('[data-testid=\"media-editor\"]'))"))->toBeFalse()
->and($page->script('window.__uploadRequest'))->toBeNull();
@@ -258,7 +235,7 @@ test('the workspace logo opens the same editor with a square 1:1 crop', function
$page = visit(route('app.workspace.settings'));
selectPhoto($page);
- waitForCropSelection($page);
+ waitForState($page, '@media-editor-selection', 'element.getBoundingClientRect().width > 0');
recordUpload($page);
$selection = cropSelectionBox($page);
diff --git a/tests/Browser/ImportedPostCardTest.php b/tests/Browser/ImportedPostCardTest.php
index 2b5e5e583..3654ee30a 100644
--- a/tests/Browser/ImportedPostCardTest.php
+++ b/tests/Browser/ImportedPostCardTest.php
@@ -15,18 +15,6 @@ use App\Models\Workspace;
use Illuminate\Support\Facades\Queue;
use Illuminate\Support\Str;
-function waitForImportedCardTestId(mixed $page, string $testId): void
-{
- $page->script(<<<JS
- (async () => {
- for (let attempt = 0; attempt < 100; attempt++) {
- if (document.querySelector('[data-testid="{$testId}"]')?.getBoundingClientRect().height > 0) return;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })();
- JS);
-}
-
/**
* @return list<string>
*/
@@ -102,7 +90,7 @@ test('an imported sent card looks like a sent post and offers only the allowed a
$this->actingAs($user);
$page = visit(route('app.posts.index', ['tab' => 'sent']));
- waitForImportedCardTestId($page, "post-card-{$post->id}");
+ waitFor($page, "@post-card-{$post->id}");
$page->assertSeeIn("@post-card-{$post->id}", __('posts.content_types.instagram_reel.label'))
->assertSeeIn("@post-card-{$post->id}", 'Posted straight from the app')
@@ -123,7 +111,7 @@ test('an imported sent card looks like a sent post and offers only the allowed a
->toBe('svg');
$page->script("document.querySelector('[data-testid=\"post-published-via-{$post->id}\"]').dispatchEvent(new PointerEvent('pointermove', {bubbles: true, pointerType: 'mouse'}))");
- waitForImportedCardTestId($page, "post-published-via-tooltip-{$post->id}");
+ waitFor($page, "@post-published-via-tooltip-{$post->id}");
$page->assertSeeIn("@post-published-via-tooltip-{$post->id}", __('posts.publish.published_directly_from', ['network' => 'Instagram']));
expect($page->script("document.querySelector('[data-testid=\"post-thumbnail-video-{$post->id}-0\"]').getAttribute('src')"))
@@ -135,12 +123,12 @@ test('an imported sent card looks like a sent post and offers only the allowed a
->toBeTrue();
$page->click("@post-card-menu-{$post->id}");
- waitForImportedCardTestId($page, "post-card-menu-content-{$post->id}");
+ waitFor($page, "@post-card-menu-content-{$post->id}");
expect(importedCardMenuItems($page, $post->id))->toBe(['post-duplicate', 'post-details-open', 'post-share-link', 'post-copy-link']);
$page->click("@post-details-open-{$post->id}");
- waitForImportedCardTestId($page, "post-details-{$post->id}");
+ waitFor($page, "@post-details-{$post->id}");
$page->assertSeeIn("@post-details-published-via-{$post->id}", 'Instagram')
->assertPresent("@post-details-published-via-icon-{$post->id}")
@@ -177,7 +165,7 @@ test('content type badges follow the display rules for each platform', function
$page = visit(route('app.posts.index', ['tab' => 'sent']));
foreach ($expectations as [$post, $contentType, $showsBadge]) {
- waitForImportedCardTestId($page, "post-card-{$post->id}");
+ waitFor($page, "@post-card-{$post->id}");
$page->assertPresent("@post-card-{$post->id}");
if ($showsBadge) {
@@ -232,12 +220,12 @@ test('on a phone an imported sent card hides the published via line and right-al
JS;
$page = visit(route('app.posts.index', ['tab' => 'sent']))->resize(390, 844);
- waitForImportedCardTestId($page, "post-actions-{$post->id}");
+ waitFor($page, "@post-actions-{$post->id}");
expect($page->script($measure))->toBe(['viaVisible' => false, 'actionsAtEnd' => true]);
$page->resize(1280, 800);
- waitForImportedCardTestId($page, "post-published-via-{$post->id}");
+ waitFor($page, "@post-published-via-{$post->id}");
expect($page->script($measure)['viaVisible'])->toBeTrue();
$page->assertNoJavaScriptErrors();
@@ -263,16 +251,16 @@ test('on a phone the details dialog of an imported post hides the published via
JS;
$page = visit(route('app.posts.index', ['tab' => 'sent']))->resize(390, 844);
- waitForImportedCardTestId($page, "post-card-menu-{$post->id}");
+ waitFor($page, "@post-card-menu-{$post->id}");
$page->click("@post-card-menu-{$post->id}");
- waitForImportedCardTestId($page, "post-details-open-{$post->id}");
+ waitFor($page, "@post-details-open-{$post->id}");
$page->click("@post-details-open-{$post->id}");
- waitForImportedCardTestId($page, "post-card-menu-details-{$post->id}");
+ waitFor($page, "@post-card-menu-details-{$post->id}");
expect($page->script($measure))->toBe(['viaVisible' => false, 'viewVisible' => true, 'menuAtEnd' => true]);
$page->resize(1280, 800);
- waitForImportedCardTestId($page, "post-details-view-{$post->id}");
+ waitFor($page, "@post-details-view-{$post->id}");
$desktop = $page->script($measure);
expect($desktop['viaVisible'])->toBeTrue()
@@ -291,13 +279,13 @@ test('a trypost sent post keeps the created by footer and shows its metrics in i
$this->actingAs($user);
$page = visit(route('app.posts.index', ['tab' => 'sent']));
- waitForImportedCardTestId($page, "post-card-menu-{$post->id}");
+ waitFor($page, "@post-card-menu-{$post->id}");
$page->assertSeeIn("@post-created-by-{$post->id}", $user->name)
->assertMissing("@post-published-via-{$post->id}");
$page->click("@post-card-menu-{$post->id}");
- waitForImportedCardTestId($page, "post-details-open-{$post->id}");
+ waitFor($page, "@post-details-open-{$post->id}");
$page->click("@post-details-open-{$post->id}");
- waitForImportedCardTestId($page, "post-details-{$post->id}");
+ waitFor($page, "@post-details-{$post->id}");
$page->assertSeeIn("@post-details-created-by-{$post->id}", $user->name)
->assertPresent("@post-details-metrics-{$post->id}")
@@ -313,11 +301,11 @@ test('a draft shows no metrics band in its details', function () {
$this->actingAs($user);
$page = visit(route('app.posts.index', ['tab' => 'drafts']));
- waitForImportedCardTestId($page, "post-card-menu-{$post->id}");
+ waitFor($page, "@post-card-menu-{$post->id}");
$page->click("@post-card-menu-{$post->id}");
- waitForImportedCardTestId($page, "post-details-open-{$post->id}");
+ waitFor($page, "@post-details-open-{$post->id}");
$page->click("@post-details-open-{$post->id}");
- waitForImportedCardTestId($page, "post-details-{$post->id}");
+ waitFor($page, "@post-details-{$post->id}");
$page->assertSeeIn("@post-details-created-by-{$post->id}", $user->name)
->assertMissing("@post-details-metrics-{$post->id}")
@@ -346,7 +334,7 @@ test('the content type badge has an icon for stories and reels and is hidden for
$page = visit(route('app.posts.index', ['tab' => 'sent']));
foreach ($expectations as [$post, $label]) {
- waitForImportedCardTestId($page, "post-card-{$post->id}");
+ waitFor($page, "@post-card-{$post->id}");
if ($label === null) {
$page->assertMissing("@post-content-type-{$post->id}");
diff --git a/tests/Browser/InsightsChannelFilterTest.php b/tests/Browser/InsightsChannelFilterTest.php
index 8fc1bd9e0..9c5b16235 100644
--- a/tests/Browser/InsightsChannelFilterTest.php
+++ b/tests/Browser/InsightsChannelFilterTest.php
@@ -75,14 +75,7 @@ test('the channel filter scopes the dashboard and keeps the channel in the url',
->click('@analytics-channel-filter');
waitFor($page, "@analytics-channel-checkbox-{$alpha->id}");
$page->click("@analytics-channel-checkbox-{$alpha->id}");
- $page->script(<<<'JS'
- (async () => {
- for (let attempt = 0; attempt < 100; attempt++) {
- if ([...new URLSearchParams(location.search).keys()].filter((key) => key.startsWith('channels')).length === 1) return;
- await new Promise((resolve) => setTimeout(resolve, 100));
- }
- })();
- JS);
+ waitForCondition($page, "[...new URLSearchParams(location.search).keys()].filter((key) => key.startsWith('channels')).length === 1");
waitFor($page, '@insights-card-followers');
$page->assertScript('[...new URLSearchParams(location.search)].filter(([key]) => key.startsWith("channels")).map(([, value]) => value)', [$alpha->id])
@@ -91,14 +84,7 @@ test('the channel filter scopes the dashboard and keeps the channel in the url',
->assertNoJavaScriptErrors();
$page->click('@insights-range-7d');
- $page->script(<<<'JS'
- (async () => {
- for (let attempt = 0; attempt < 100; attempt++) {
- if (new URLSearchParams(location.search).get('range') === '7d') return;
- await new Promise((resolve) => setTimeout(resolve, 100));
- }
- })();
- JS);
+ waitForQueryParameter($page, 'range', '7d');
$page->assertScript('[...new URLSearchParams(location.search)].filter(([key]) => key.startsWith("channels")).map(([, value]) => value)', [$alpha->id])
->assertNoJavaScriptErrors();
@@ -195,14 +181,7 @@ test('a channel without data shows the filtered empty state and history navigati
$page = visit(route('app.insights'));
waitFor($page, '@insights-range-7d');
$page->click('@insights-range-7d');
- $page->script(<<<'JS'
- (async () => {
- for (let attempt = 0; attempt < 100; attempt++) {
- if (new URLSearchParams(location.search).get('range') === '7d') return;
- await new Promise((resolve) => setTimeout(resolve, 100));
- }
- })();
- JS);
+ waitForQueryParameter($page, 'range', '7d');
waitFor($page, '@analytics-channel-filter');
$page->click('@analytics-channel-filter');
waitFor($page, "@analytics-channel-checkbox-{$silent->id}");
@@ -215,14 +194,7 @@ test('a channel without data shows the filtered empty state and history navigati
->assertScript('new URLSearchParams(location.search).get("range")', '7d');
$page->script('history.back()');
- $page->script(<<<'JS'
- (async () => {
- for (let attempt = 0; attempt < 100; attempt++) {
- if (location.pathname.endsWith('/insights') && !location.search.includes('range=7d')) return;
- await new Promise((resolve) => setTimeout(resolve, 100));
- }
- })();
- JS);
+ waitForCondition($page, "location.pathname.endsWith('/insights') && !location.search.includes('range=7d')");
waitFor($page, '@analytics-summary-followers');
$page->assertScript('location.pathname.endsWith("/insights") && !location.search.includes("channels")', true)
diff --git a/tests/Browser/InsightsParityTest.php b/tests/Browser/InsightsParityTest.php
index 6e2d00718..917baaf00 100644
--- a/tests/Browser/InsightsParityTest.php
+++ b/tests/Browser/InsightsParityTest.php
@@ -18,23 +18,6 @@ use App\Models\User;
use App\Models\Workspace;
use Illuminate\Support\Facades\Queue;
-function waitForInsightsParityCondition(mixed $page, string $condition): void
-{
- $page->script(<<<JS
- (async () => {
- for (let attempt = 0; attempt < 200; attempt++) {
- if ({$condition}) return;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })();
- JS);
-}
-
-function waitForInsightsParityTestId(mixed $page, string $testId): void
-{
- waitForInsightsParityCondition($page, "document.querySelector('[data-testid=\"{$testId}\"]')?.getBoundingClientRect().height > 0");
-}
-
const INSIGHTS_PARITY_AVATAR = 'data:image/svg+xml;utf8,%3Csvg xmlns=%22http://www.w3.org/2000/svg%22 width=%2240%22 height=%2240%22%3E%3Crect width=%2240%22 height=%2240%22 fill=%22%23e11d48%22/%3E%3C/svg%3E';
/**
@@ -118,10 +101,10 @@ test('the header offers CSV and Markdown exports of the filtered page and explai
$this->actingAs($user);
$page = visit(route('app.insights', ['range' => '7d', 'channels' => [$instagram->id]]));
- waitForInsightsParityTestId($page, 'insights-export');
+ waitFor($page, '@insights-export');
$page->click('@insights-export');
- waitForInsightsParityTestId($page, 'insights-export-csv');
+ waitFor($page, '@insights-export-csv');
$csv = (string) $page->script('document.querySelector("[data-testid=insights-export-csv]").getAttribute("href")');
$markdown = (string) $page->script('document.querySelector("[data-testid=insights-export-md]").getAttribute("href")');
@@ -138,7 +121,7 @@ test('the header offers CSV and Markdown exports of the filtered page and explai
$page->assertScript('getComputedStyle(document.querySelector("[data-testid=insights-sync-status]")).backgroundColor !== "rgba(0, 0, 0, 0)"', true)
->click('@insights-sync-status');
- waitForInsightsParityTestId($page, 'insights-sync-popover');
+ waitFor($page, '@insights-sync-popover');
$page->assertSeeIn('@insights-sync-popover', 'How Insights stay updated')
->assertSeeIn('@insights-sync-new-posts', 'New posts are picked up daily.')
@@ -152,15 +135,15 @@ test('followers and posts charts show network logos and say how many channels ar
$this->actingAs($user);
$page = visit(route('app.insights'));
- waitForInsightsParityTestId($page, 'accounts-unovis-bar-chart');
- waitForInsightsParityCondition($page, 'document.querySelectorAll("[data-testid=analytics-axis-channel]").length >= 4');
+ waitFor($page, '@accounts-unovis-bar-chart');
+ waitForCount($page, '@analytics-axis-channel', 4, '>=');
$page->assertScript('document.querySelectorAll("[data-testid=analytics-axis-channel]").length', 4)
->assertScript('document.querySelector("[data-testid=analytics-followers-subtitle]")?.textContent.includes("Showing")', false);
$page->navigate(route('app.insights', ['channels' => [$instagram->id]]));
- waitForInsightsParityTestId($page, 'analytics-followers-subtitle');
- waitForInsightsParityCondition($page, 'document.querySelectorAll("[data-testid=analytics-axis-channel]").length >= 2');
+ waitFor($page, '@analytics-followers-subtitle');
+ waitForCount($page, '@analytics-axis-channel', 2, '>=');
$page->assertSeeIn('@analytics-followers-subtitle', 'Showing 1 of 2 channels. Filter by channel to see a different set.')
->assertSeeIn('@analytics-posts-subtitle', 'Showing 1 of 2 channels.')
@@ -175,13 +158,13 @@ test('a channel whose connection is lost shows the disconnected dot in the filte
$this->actingAs($user);
$page = visit(route('app.insights'));
- waitForInsightsParityTestId($page, 'analytics-channel-filter');
- waitForInsightsParityCondition($page, 'document.querySelectorAll("[data-testid=analytics-axis-channel] [data-testid^=channel-avatar-disconnected]").length >= 2');
+ waitFor($page, '@analytics-channel-filter');
+ waitForCount($page, '@analytics-axis-channel [data-testid^=channel-avatar-disconnected]', 2, '>=');
$page->assertScript('document.querySelectorAll("[data-testid=analytics-axis-channel] [data-testid^=channel-avatar-disconnected]").length', 2)
->assertScript("document.querySelectorAll('[data-testid=\"channel-avatar-disconnected-{$facebook->id}\"]').length >= 1", true)
->click('@analytics-channel-filter');
- waitForInsightsParityCondition($page, "document.querySelectorAll('[data-testid=\"channel-avatar-disconnected-{$facebook->id}\"]').length >= 2");
+ waitForCount($page, "@channel-avatar-disconnected-{$facebook->id}", 2, '>=');
$page->assertNoJavaScriptErrors();
});
@@ -191,8 +174,8 @@ test('the insights dashboard shows channel avatars, explains itself, sorts and c
$this->actingAs($user);
$page = visit(route('app.insights'));
- waitForInsightsParityTestId($page, 'accounts-unovis-bar-chart');
- waitForInsightsParityCondition($page, 'document.querySelectorAll("[data-testid=analytics-axis-channel]").length >= 4');
+ waitFor($page, '@accounts-unovis-bar-chart');
+ waitForCount($page, '@analytics-axis-channel', 4, '>=');
$page->assertScript('document.querySelectorAll("[data-testid=analytics-axis-channel] [data-slot=avatar] img").length', 2)
->assertScript('document.querySelectorAll("[data-testid=analytics-axis-channel] [data-slot=avatar] > div").length', 2)
@@ -200,7 +183,7 @@ test('the insights dashboard shows channel avatars, explains itself, sorts and c
->assertScript('document.querySelectorAll("[data-testid=analytics-top-post-channel]").length >= 2', true)
->assertNoJavaScriptErrors();
- waitForInsightsParityTestId($page, 'analytics-summary-posts-about');
+ waitFor($page, '@analytics-summary-posts-about');
foreach (['posts', 'followers', 'reactions', 'comments', 'engagement_rate'] as $metric) {
$page->assertPresent("@analytics-summary-{$metric}-about");
@@ -211,43 +194,43 @@ test('the insights dashboard shows channel avatars, explains itself, sorts and c
}
$page->hover('@analytics-summary-posts-about');
- waitForInsightsParityTestId($page, 'analytics-summary-posts-about-content');
+ waitFor($page, '@analytics-summary-posts-about-content');
$page->assertSeeIn('@analytics-summary-posts-about-content', 'Number of posts published');
$page->hover('@analytics-performance-about');
- waitForInsightsParityTestId($page, 'analytics-performance-about-content');
+ waitFor($page, '@analytics-performance-about-content');
$page->assertSeeIn('@analytics-performance-about-content', 'Totals per channel')
->assertNoJavaScriptErrors();
- waitForInsightsParityTestId($page, 'analytics-performance-sort-reactions');
+ waitFor($page, '@analytics-performance-sort-reactions');
$order = 'Array.from(document.querySelectorAll("tbody th[scope=row]")).map((cell) => (cell.innerText.match(/Alpha|Bravo/) || [""])[0]).join(",")';
$page->assertScript('document.querySelector("[data-testid=analytics-performance-columns]").closest("table") === null', true)
->click('@analytics-performance-sort-reactions');
- waitForInsightsParityCondition($page, 'document.querySelector("[data-testid=analytics-performance-column-reactions]").getAttribute("aria-sort") === "descending"');
+ waitForState($page, '@analytics-performance-column-reactions', "element.getAttribute('aria-sort') === 'descending'");
$descending = $page->script($order);
$page->click('@analytics-performance-sort-reactions');
- waitForInsightsParityCondition($page, 'document.querySelector("[data-testid=analytics-performance-column-reactions]").getAttribute("aria-sort") === "ascending"');
+ waitForState($page, '@analytics-performance-column-reactions', "element.getAttribute('aria-sort') === 'ascending'");
$ascending = $page->script($order);
expect($descending)->toContain('Alpha')
->and($ascending)->toBe(implode(',', array_reverse(explode(',', $descending))));
$page->click('@analytics-performance-sort-channel');
- waitForInsightsParityCondition($page, 'document.querySelector("[data-testid=analytics-performance-channel-header]").getAttribute("aria-sort") === "ascending"');
+ waitForState($page, '@analytics-performance-channel-header', "element.getAttribute('aria-sort') === 'ascending'");
expect($page->script($order))->toBe('Alpha,Bravo');
$page->assertNoJavaScriptErrors();
- waitForInsightsParityTestId($page, 'analytics-performance-columns');
+ waitFor($page, '@analytics-performance-columns');
$headers = 'Array.from(document.querySelectorAll("[data-testid^=analytics-performance-column-]")).map((cell) => cell.dataset.testid.replace("analytics-performance-column-", "")).join(",")';
$page->assertScript($headers, 'posts,reactions,comments,engagement_rate')
->click('@analytics-performance-columns');
- waitForInsightsParityTestId($page, 'analytics-performance-columns-menu');
+ waitFor($page, '@analytics-performance-columns-menu');
$page->assertSeeIn('@analytics-performance-columns-menu', 'Columns')
->assertScript('document.querySelector("[data-testid=analytics-performance-columns-posts] [role=checkbox]")?.getAttribute("data-state")', 'checked')
@@ -267,22 +250,22 @@ test('the insights dashboard shows channel avatars, explains itself, sorts and c
foreach (['reposts', 'impressions', 'clicks', 'shares', 'saves', 'reach'] as $metric) {
$page->click("@analytics-performance-columns-{$metric}");
}
- waitForInsightsParityCondition($page, "{$headers} === 'posts,reactions,engagement_rate,views'");
+ waitForCondition($page, "{$headers} === 'posts,reactions,engagement_rate,views'");
$page->assertScript($headers, 'posts,reactions,engagement_rate,views')
->assertSeeIn('@analytics-performance-column-views', 'Views');
$page->navigate(route('app.insights'));
- waitForInsightsParityTestId($page, 'analytics-performance-columns');
+ waitFor($page, '@analytics-performance-columns');
$page->assertScript($headers, 'posts,reactions,engagement_rate,views')
->assertNoJavaScriptErrors();
- waitForInsightsParityTestId($page, 'analytics-top-post-link');
+ waitFor($page, '@analytics-top-post-link');
$path = $page->script('location.pathname');
$page->click('[data-testid="analytics-top-post"] >> nth=0');
- waitForInsightsParityTestId($page, "post-details-{$post->id}");
+ waitFor($page, "@post-details-{$post->id}");
$page->assertScript('location.pathname', $path)
->assertScript('new URLSearchParams(location.search).has("post")', false)
diff --git a/tests/Browser/InsightsShareChartTest.php b/tests/Browser/InsightsShareChartTest.php
index 552c70753..101105145 100644
--- a/tests/Browser/InsightsShareChartTest.php
+++ b/tests/Browser/InsightsShareChartTest.php
@@ -80,10 +80,9 @@ test('the followers chart opens a share card in a TryPost tint that turns into a
$page->click('@share-chart-color-green')
->assertAttribute('@share-chart-color-green', 'aria-checked', 'true');
- waitForCondition($page, <<<'JS'
+ waitForState($page, '@share-chart-preview', <<<'JS'
(() => {
- const canvas = document.querySelector('[data-testid="share-chart-preview"]');
- const [r, g, b] = canvas.getContext('2d').getImageData(2, Math.round(canvas.height / 2), 1, 1).data;
+ const [r, g, b] = element.getContext('2d').getImageData(2, Math.round(element.height / 2), 1, 1).data;
return `${r},${g},${b}` === '217,241,209';
})()
diff --git a/tests/Browser/LabelFilterPopoverTest.php b/tests/Browser/LabelFilterPopoverTest.php
index 01899bde7..ad1162354 100644
--- a/tests/Browser/LabelFilterPopoverTest.php
+++ b/tests/Browser/LabelFilterPopoverTest.php
@@ -6,31 +6,9 @@ use App\Models\User;
use App\Models\Workspace;
use App\Models\WorkspaceLabel;
-function waitForLabelPopoverTestId(mixed $page, string $testId): void
-{
- $page->script(<<<JS
- (async () => {
- const selector = '[data-testid="{$testId}"]';
- for (let attempt = 0; attempt < 200; attempt++) {
- const element = document.querySelector(selector);
- if (element && element.getBoundingClientRect().height > 0) return;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })();
- JS);
-}
-
function waitForLabelPopoverUrl(mixed $page, string $condition): void
{
- $page->script(<<<JS
- (async () => {
- for (let attempt = 0; attempt < 100; attempt++) {
- const params = new URLSearchParams(location.search);
- if ({$condition}) return;
- await new Promise((resolve) => setTimeout(resolve, 100));
- }
- })();
- JS);
+ waitForCondition($page, "((params) => {$condition})(new URLSearchParams(location.search))");
}
test('the label filter offers untagged, clears the selection and links to the labels page', function () {
@@ -43,9 +21,9 @@ test('the label filter offers untagged, clears the selection and links to the la
$this->actingAs($user);
$page = visit(route('app.posts.index', ['tab' => 'drafts']));
- waitForLabelPopoverTestId($page, 'posts-label-filter');
+ waitFor($page, '@posts-label-filter');
$page->click('@posts-label-filter');
- waitForLabelPopoverTestId($page, 'posts-label-untagged');
+ waitFor($page, '@posts-label-untagged');
$page->assertScript('document.querySelector("[data-testid=posts-label-settings]").getAttribute("href")', route('app.labels.index', absolute: false))
->assertPresent('@posts-label-clear')
@@ -75,16 +53,16 @@ test('the label filter offers to create a label when the workspace has none', fu
$this->actingAs($user);
$page = visit(route('app.posts.index', ['tab' => 'drafts']));
- waitForLabelPopoverTestId($page, 'posts-label-filter');
+ waitFor($page, '@posts-label-filter');
$page->click('@posts-label-filter');
- waitForLabelPopoverTestId($page, 'posts-label-empty');
+ waitFor($page, '@posts-label-empty');
$page->assertMissing('@posts-label-untagged')
->assertMissing('@posts-label-settings')
->assertSeeIn('@posts-label-empty', __('posts.no_labels'))
->assertMissing('@posts-label-create')
->click('@posts-label-empty-create');
- waitForLabelPopoverTestId($page, 'posts-label-new-name');
+ waitFor($page, '@posts-label-new-name');
expect($page->script(<<<'JS'
(() => {
@@ -99,9 +77,7 @@ test('the label filter offers to create a label when the workspace has none', fu
$page->fill('@posts-label-new-name', 'Launch')
->click('@submit-posts-label-new');
- for ($attempt = 0; $attempt < 40 && ! WorkspaceLabel::query()->where('workspace_id', $workspace->id)->where('name', 'Launch')->exists(); $attempt++) {
- $page->script('new Promise((resolve) => setTimeout(resolve, 100))');
- }
+ waitForDatabase($page, fn () => WorkspaceLabel::query()->where('workspace_id', $workspace->id)->where('name', 'Launch')->exists());
expect(WorkspaceLabel::query()->where('workspace_id', $workspace->id)->where('name', 'Launch')->exists())->toBeTrue();
@@ -119,9 +95,9 @@ test('the label filter search ignores accents and hides untagged when it does no
$this->actingAs($user);
$page = visit(route('app.posts.index', ['tab' => 'drafts']));
- waitForLabelPopoverTestId($page, 'posts-label-filter');
+ waitFor($page, '@posts-label-filter');
$page->click('@posts-label-filter');
- waitForLabelPopoverTestId($page, 'posts-label-untagged');
+ waitFor($page, '@posts-label-untagged');
$page->fill('@posts-label-search', 'promocao')
->assertVisible("@posts-label-option-{$promo->id}")
diff --git a/tests/Browser/LabelRowMenuTest.php b/tests/Browser/LabelRowMenuTest.php
index 3010da415..a62a720dd 100644
--- a/tests/Browser/LabelRowMenuTest.php
+++ b/tests/Browser/LabelRowMenuTest.php
@@ -7,20 +7,6 @@ use App\Models\User;
use App\Models\Workspace;
use App\Models\WorkspaceLabel;
-function waitForLabelMenuTestId(mixed $page, string $testId): void
-{
- $page->script(<<<JS
- (async () => {
- const sel = '[data-testid="{$testId}"]';
- for (let i = 0; i < 100; i++) {
- const el = document.querySelector(sel);
- if (el && el.getBoundingClientRect().height > 0) return;
- await new Promise((r) => setTimeout(r, 50));
- }
- })();
- JS);
-}
-
function labelMenuOwner(): array
{
$user = User::factory()->create();
@@ -37,9 +23,9 @@ function labelMenuOwner(): array
function assertLabelFilterSelected(mixed $page, string $testId, string $labelId): void
{
- waitForLabelMenuTestId($page, "{$testId}-filter");
+ waitFor($page, "@{$testId}-filter");
$page->click("@{$testId}-filter");
- waitForLabelMenuTestId($page, "{$testId}-checkbox-{$labelId}");
+ waitFor($page, "@{$testId}-checkbox-{$labelId}");
$page->assertAttribute("@{$testId}-checkbox-{$labelId}", 'data-state', 'checked')
->assertNoJavaScriptErrors();
}
@@ -49,9 +35,9 @@ test('label row menu opens posts filtered by the label in a new tab', function (
$this->actingAs($user);
$page = visit(route('app.labels.index'));
- waitForLabelMenuTestId($page, "label-menu-{$label->id}");
+ waitFor($page, "@label-menu-{$label->id}");
$page->click("@label-menu-{$label->id}");
- waitForLabelMenuTestId($page, "label-view-posts-{$label->id}");
+ waitFor($page, "@label-view-posts-{$label->id}");
$links = $page->script(<<<JS
(() => ['label-view-posts-{$label->id}'].map((id) => {
@@ -81,7 +67,7 @@ test('the labels page without labels shows a centered illustration and a create
$this->actingAs($user);
$page = visit(route('app.labels.index'));
- waitForLabelMenuTestId($page, 'labels-empty');
+ waitFor($page, '@labels-empty');
$page->assertVisible('@labels-empty-illustration')
->assertMissing('@header-title')
@@ -115,7 +101,7 @@ test('the labels page without labels shows a centered illustration and a create
JS))->toBe([true, true]);
$page->click('@labels-empty-create');
- waitForLabelMenuTestId($page, 'create-label-sheet');
+ waitFor($page, '@create-label-sheet');
$page->assertVisible('@create-label-sheet')->assertNoJavaScriptErrors();
});
@@ -124,7 +110,7 @@ test('a search without results keeps the header and search, and clearing it neve
$this->actingAs($user);
$page = visit(route('app.labels.index', ['search' => 'nothing-matches']));
- waitForLabelMenuTestId($page, 'empty-state');
+ waitFor($page, '@empty-state');
$page->assertVisible('@header-title')
->assertVisible('@create-label-button')
@@ -162,7 +148,7 @@ test('a long labels list starts at the top and scrolls normally', function () {
$this->actingAs($user);
$page = visit(route('app.labels.index'));
- waitForLabelMenuTestId($page, "label-row-{$label->id}");
+ waitFor($page, "@label-row-{$label->id}");
expect($page->script(<<<'JS'
(() => {
@@ -186,7 +172,7 @@ test('a label row shows its color, how many posts use it and its actions in one
$this->actingAs($user);
$page = visit(route('app.labels.index'));
- waitForLabelMenuTestId($page, "label-row-{$label->id}");
+ waitFor($page, "@label-row-{$label->id}");
$page->assertSeeIn("@label-posts-count-{$label->id}", trans_choice('labels.meta.posts', 1, ['count' => 1]));
@@ -194,11 +180,11 @@ test('a label row shows its color, how many posts use it and its actions in one
->toBe('rgb(22, 163, 74)');
$page->click("@label-menu-{$label->id}");
- waitForLabelMenuTestId($page, "edit-label-{$label->id}");
+ waitFor($page, "@edit-label-{$label->id}");
$page->assertVisible("@delete-label-{$label->id}")
->click("@edit-label-{$label->id}");
- waitForLabelMenuTestId($page, 'edit-label-dialog');
+ waitFor($page, '@edit-label-dialog');
$page->assertVisible('@edit-label-dialog')->assertNoJavaScriptErrors();
});
diff --git a/tests/Browser/LinkCardPreviewTest.php b/tests/Browser/LinkCardPreviewTest.php
index b969579da..ad5b1a5ff 100644
--- a/tests/Browser/LinkCardPreviewTest.php
+++ b/tests/Browser/LinkCardPreviewTest.php
@@ -66,47 +66,6 @@ function seedLinkCardPreviewPost(
return [$post, $account];
}
-function waitForLinkCardPreviewTestId(mixed $page, string $testId): void
-{
- $page->script(<<<JS
- (async () => {
- for (let attempt = 0; attempt < 300; attempt++) {
- const dialog = document.querySelector('[data-testid="post-composer-dialog"]');
- if (dialog?.getAttribute('data-state') === 'open'
- && dialog.getAnimations().every((animation) => animation.playState !== 'running')
- && document.querySelector('[data-testid="{$testId}"]')?.getBoundingClientRect().height > 0) return;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })();
- JS);
-}
-
-function waitForLinkCardPreviewText(mixed $page, string $text): void
-{
- $encoded = json_encode($text);
-
- $page->script(<<<JS
- (async () => {
- for (let attempt = 0; attempt < 300; attempt++) {
- if (document.querySelector('[data-testid="link-card-title"]')?.textContent.includes({$encoded})) return;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })();
- JS);
-}
-
-function waitForLinkCardPreviewGone(mixed $page): void
-{
- $page->script(<<<'JS'
- (async () => {
- for (let attempt = 0; attempt < 300; attempt++) {
- if (!document.querySelector('[data-testid="link-card"]')) return;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })();
- JS);
-}
-
test('facebook linkedin and mastodon previews render fetched link cards', function (Platform $platform) {
$url = "https://93.184.216.34/{$platform->value}";
Http::fake([$url => Http::response('<meta property="og:title" content="Article card">')]);
@@ -120,8 +79,9 @@ test('facebook linkedin and mastodon previews render fetched link cards', functi
});
$page = visit(route('app.posts.edit', $post));
- waitForLinkCardPreviewTestId($page, 'composer-preview-frame');
- waitForLinkCardPreviewText($page, 'Article card');
+ waitForOpen($page, '@post-composer-dialog');
+ waitFor($page, '@composer-preview-frame');
+ waitForState($page, '@link-card-title', "element.textContent.includes('Article card')");
$page->assertSeeIn('@link-card-title', 'Article card')
->assertPresent('@link-card')
@@ -138,12 +98,13 @@ test('removing a url removes its visible card', function () {
[$post, $account] = seedLinkCardPreviewPost(Platform::LinkedIn, 'https://93.184.216.34/article');
$page = visit(route('app.posts.edit', $post));
- waitForLinkCardPreviewTestId($page, "composer-caption-{$account->id}");
- waitForLinkCardPreviewText($page, 'Article card');
+ waitForOpen($page, '@post-composer-dialog');
+ waitFor($page, "@composer-caption-{$account->id}");
+ waitForState($page, '@link-card-title', "element.textContent.includes('Article card')");
$page->assertSeeIn('@link-card-title', 'Article card')
->clear("@composer-caption-{$account->id}");
- waitForLinkCardPreviewGone($page);
+ waitForGone($page, '@link-card');
$page->assertMissing('@link-card')
->assertNoJavaScriptErrors();
@@ -158,18 +119,19 @@ test('a failed fetch clears the previous card and a later url can recover', func
[$post, $account] = seedLinkCardPreviewPost(Platform::LinkedIn, 'https://93.184.216.34/article');
$page = visit(route('app.posts.edit', $post));
- waitForLinkCardPreviewTestId($page, "composer-caption-{$account->id}");
- waitForLinkCardPreviewText($page, 'Article card');
+ waitForOpen($page, '@post-composer-dialog');
+ waitFor($page, "@composer-caption-{$account->id}");
+ waitForState($page, '@link-card-title', "element.textContent.includes('Article card')");
$page->assertSeeIn('@link-card-title', 'Article card')
->fill("@composer-caption-{$account->id}", 'https://93.184.216.34/broken');
Execution::instance()->waitForExpectation(fn () => Http::assertSentCount(2));
- waitForLinkCardPreviewGone($page);
+ waitForGone($page, '@link-card');
$page->assertMissing('@link-card')
->fill("@composer-caption-{$account->id}", 'https://93.184.216.34/recovered');
- waitForLinkCardPreviewText($page, 'Recovered card');
+ waitForState($page, '@link-card-title', "element.textContent.includes('Recovered card')");
$page->assertSeeIn('@link-card-title', 'Recovered card')
->assertNoJavaScriptErrors();
@@ -192,7 +154,8 @@ test('a pending response cannot overwrite a newer card or revive a removed url',
try {
[$post, $account] = seedLinkCardPreviewPost(Platform::LinkedIn, 'https://93.184.216.34/slow');
$page = visit(route('app.posts.edit', $post));
- waitForLinkCardPreviewTestId($page, "composer-caption-{$account->id}");
+ waitForOpen($page, '@post-composer-dialog');
+ waitFor($page, "@composer-caption-{$account->id}");
Execution::instance()->waitForExpectation(function () use (&$started) {
expect($started)->toBeTrue();
@@ -201,7 +164,7 @@ test('a pending response cannot overwrite a newer card or revive a removed url',
$page->fill("@composer-caption-{$account->id}", $removeUrl ? '' : 'https://93.184.216.34/current');
if (! $removeUrl) {
- waitForLinkCardPreviewText($page, 'Current card');
+ waitForState($page, '@link-card-title', "element.textContent.includes('Current card')");
$page->assertSeeIn('@link-card-title', 'Current card');
}
} finally {
@@ -234,7 +197,8 @@ test('attached media suppresses fetching until it is removed', function () {
]]);
$page = visit(route('app.posts.edit', $post));
- waitForLinkCardPreviewTestId($page, "composer-{$account->id}-media-item");
+ waitForOpen($page, '@post-composer-dialog');
+ waitFor($page, "@composer-{$account->id}-media-item");
$page->assertPresent("@composer-{$account->id}-media-item")
->assertMissing('@link-card');
@@ -242,7 +206,7 @@ test('attached media suppresses fetching until it is removed', function () {
Http::assertNothingSent();
$page->click("@composer-{$account->id}-remove-0");
- waitForLinkCardPreviewText($page, 'Article card');
+ waitForState($page, '@link-card-title', "element.textContent.includes('Article card')");
$page->assertSeeIn('@link-card-title', 'Article card')
->assertNoJavaScriptErrors();
@@ -250,18 +214,6 @@ test('attached media suppresses fetching until it is removed', function () {
Http::assertSentCount(1);
});
-function waitForLinkCardPreviewMissing(mixed $page, string $testId): void
-{
- $page->script(<<<JS
- (async () => {
- for (let attempt = 0; attempt < 300; attempt++) {
- if (!document.querySelector('[data-testid="{$testId}"]')) return;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })();
- JS);
-}
-
test('the editor link card can be dropped and the post saves without it', function (Platform $platform) {
$url = 'https://93.184.216.34/article';
Http::fake([$url => Http::response('<meta property="og:title" content="Article card"><meta property="og:description" content="A great read">')]);
@@ -269,12 +221,13 @@ test('the editor link card can be dropped and the post saves without it', functi
$card = "composer-link-card-{$account->id}";
$page = visit(route('app.posts.edit', $post));
- waitForLinkCardPreviewTestId($page, $card);
+ waitForOpen($page, '@post-composer-dialog');
+ waitFor($page, "@{$card}");
$page->assertSeeIn("@{$card}-title", 'Article card')
->assertPresent("@{$card}-replace")
->click("@{$card}-remove");
- waitForLinkCardPreviewMissing($page, $card);
+ waitForGone($page, "@{$card}");
$page->assertMissing("@{$card}")
->assertMissing('@link-card')
@@ -294,7 +247,8 @@ test('the threads link card cannot be dropped because threads always shows it',
$card = "composer-link-card-{$account->id}";
$page = visit(route('app.posts.edit', $post));
- waitForLinkCardPreviewTestId($page, $card);
+ waitForOpen($page, '@post-composer-dialog');
+ waitFor($page, "@{$card}");
$page->assertPresent("@{$card}-replace")
->assertMissing("@{$card}-remove")
@@ -313,10 +267,12 @@ test('replacing the link card with media attaches the card image', function () {
$card = "composer-link-card-{$account->id}";
$page = visit(route('app.posts.edit', $post));
- waitForLinkCardPreviewTestId($page, $card);
+ waitForOpen($page, '@post-composer-dialog');
+ waitFor($page, "@{$card}");
$page->click("@{$card}-replace");
- waitForLinkCardPreviewTestId($page, "composer-{$account->id}-media-item-0");
+ waitForOpen($page, '@post-composer-dialog');
+ waitFor($page, "@composer-{$account->id}-media-item-0");
$page->assertMissing("@{$card}")
->assertNoJavaScriptErrors()
@@ -341,21 +297,23 @@ test('the shared step editor shows no link card and the network card does', func
]);
$page = visit(route('app.posts.create'));
- waitForLinkCardPreviewTestId($page, 'composer-add-account');
+ waitForOpen($page, '@post-composer-dialog');
+ waitFor($page, '@composer-add-account');
$page->fill('@composer-base-content', "Read {$url}")
->click('@composer-add-account')
->click("@composer-account-option-{$facebook->id}")
->click("@composer-account-option-{$linkedin->id}")
->click("@composer-account-{$facebook->id}");
- waitForLinkCardPreviewText($page, 'Article card');
+ waitForState($page, '@link-card-title', "element.textContent.includes('Article card')");
$page->assertPresent('@composer-next')
->assertPresent('@link-card')
->assertMissing("@composer-link-card-{$facebook->id}")
->assertMissing("@composer-link-card-{$linkedin->id}")
->click('@composer-next');
- waitForLinkCardPreviewTestId($page, "composer-link-card-{$facebook->id}");
+ waitForOpen($page, '@post-composer-dialog');
+ waitFor($page, "@composer-link-card-{$facebook->id}");
$page->assertSeeIn("@composer-link-card-{$facebook->id}-title", 'Article card')
->assertNoJavaScriptErrors();
@@ -372,13 +330,15 @@ test('a dropped link card comes back when the link changes', function () {
$card = "composer-link-card-{$account->id}";
$page = visit(route('app.posts.edit', $post));
- waitForLinkCardPreviewTestId($page, $card);
+ waitForOpen($page, '@post-composer-dialog');
+ waitFor($page, "@{$card}");
$page->click("@{$card}-remove");
- waitForLinkCardPreviewMissing($page, $card);
+ waitForGone($page, "@{$card}");
$page->fill("@composer-caption-{$account->id}", "Read {$other}");
- waitForLinkCardPreviewTestId($page, $card);
+ waitForOpen($page, '@post-composer-dialog');
+ waitFor($page, "@{$card}");
$page->assertSeeIn("@{$card}-title", 'Other card')
->assertNoJavaScriptErrors()
diff --git a/tests/Browser/LinkedInCommentTest.php b/tests/Browser/LinkedInCommentTest.php
index f3b259f23..4be1b2af2 100644
--- a/tests/Browser/LinkedInCommentTest.php
+++ b/tests/Browser/LinkedInCommentTest.php
@@ -75,13 +75,12 @@ test('a linkedin post takes one comment that shows under the post in the preview
test('shift enter breaks the line in a linkedin caption and comment instead of opening a thread', function () {
$post = linkedInCommentPost('linkedin', ContentType::LinkedInPost);
$caption = "@composer-caption-{$post->social_account_id}";
- $captionHtml = "document.querySelector('[data-testid=\"composer-caption-{$post->social_account_id}\"]').innerHTML";
$page = visit(route('app.posts.edit', $post))->resize(1280, 900);
waitFor($page, $caption);
$page->keys($caption, 'End')->keys($caption, 'Shift+Enter');
- waitForCondition($page, "{$captionHtml}.includes('<br')");
+ waitForState($page, $caption, "element.innerHTML.includes('<br')");
$page->assertMissing('@thread-reply-0')
->assertPresent('@thread-start')
@@ -90,7 +89,7 @@ test('shift enter breaks the line in a linkedin caption and comment instead of o
$page->fill('@thread-reply-0', 'First line')
->keys('@thread-reply-0', 'Shift+Enter');
- waitForCondition($page, "document.querySelector('[data-testid=\"thread-reply-0\"]')?.value === 'First line\\n'");
+ waitForState($page, '@thread-reply-0', "element.value === 'First line\\n'");
$page->assertMissing('@thread-reply-1')->assertNoJavaScriptErrors();
});
diff --git a/tests/Browser/LoginLocaleAppliedTest.php b/tests/Browser/LoginLocaleAppliedTest.php
index cb0b1e85f..c8aac79c1 100644
--- a/tests/Browser/LoginLocaleAppliedTest.php
+++ b/tests/Browser/LoginLocaleAppliedTest.php
@@ -21,7 +21,7 @@ test('the app renders in the user locale right after logging in', function () {
$page->fill('password', 'password');
$page->click('@login-submit');
- $page->script('(async () => { for (let i = 0; i < 150; i++) { if (location.pathname !== "/login") return; await new Promise((r) => setTimeout(r, 50)); } })();');
+ waitForCondition($page, "location.pathname !== '/login'");
$page->assertSee(__('sidebar.groups.posts', [], 'ja'))
->assertDontSee(__('sidebar.groups.posts', [], 'en'));
diff --git a/tests/Browser/McpSettingsTest.php b/tests/Browser/McpSettingsTest.php
index 46fcbdd79..ea2f42faf 100644
--- a/tests/Browser/McpSettingsTest.php
+++ b/tests/Browser/McpSettingsTest.php
@@ -6,32 +6,6 @@ use App\Models\AccessToken;
use App\Models\User;
use App\Models\Workspace;
-function waitForMcpSettingsTestId(mixed $page, string $testId): void
-{
- $page->script(<<<JS
- (async () => {
- const sel = '[data-testid="{$testId}"]';
- for (let i = 0; i < 100; i++) {
- const el = document.querySelector(sel);
- if (el && el.getBoundingClientRect().height > 0) return;
- await new Promise((r) => setTimeout(r, 50));
- }
- })();
- JS);
-}
-
-function waitForMcpSettingsTestIdGone(mixed $page, string $testId): void
-{
- $page->script(<<<JS
- (async () => {
- for (let i = 0; i < 50; i++) {
- if (!document.querySelector('[data-testid="{$testId}"]')) return;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })()
- JS);
-}
-
/**
* @return list<string>
*/
@@ -60,13 +34,13 @@ test('disconnecting an MCP app asks for the translated disconnect keyword, not t
$keyword = __('channels.disconnect_modal.keyword');
$page = visit(route('app.mcp.index'));
- waitForMcpSettingsTestId($page, "mcp-connected-menu-{$clientId}");
+ waitFor($page, "@mcp-connected-menu-{$clientId}");
$page->assertAttribute('@mcp-tab-connected', 'aria-selected', 'true')
->assertVisible('@mcp-connected-logo-claude');
$page->click("@mcp-connected-menu-{$clientId}");
- waitForMcpSettingsTestId($page, "mcp-disconnect-{$clientId}");
+ waitFor($page, "@mcp-disconnect-{$clientId}");
$page->click("@mcp-disconnect-{$clientId}")
->assertVisible('@confirm-delete-modal');
@@ -124,14 +98,14 @@ test('the MCP settings open on the connected tab, whose empty state leads to the
$this->actingAs($user->fresh());
$page = visit(route('app.mcp.index'));
- waitForMcpSettingsTestId($page, 'mcp-connected-empty');
+ waitFor($page, '@mcp-connected-empty');
$page->assertAttribute('@mcp-tab-connected', 'aria-selected', 'true')
->assertVisible('@mcp-empty-illustration')
->assertSeeIn('@mcp-connected-empty', __('mcp.connected_empty_title'))
->assertSeeIn('@mcp-connected-empty-connect', __('mcp.tabs.connect'))
->click('@mcp-connected-empty-connect');
- waitForMcpSettingsTestId($page, 'mcp-connect-claude');
+ waitFor($page, '@mcp-connect-claude');
expect(mcpSettingsTestIds($page, '[data-testid^=mcp-primary-client-]'))->toBe(['mcp-primary-client-claude', 'mcp-primary-client-chatgpt', 'mcp-primary-client-other']);
@@ -140,16 +114,16 @@ test('the MCP settings open on the connected tab, whose empty state leads to the
->assertAttribute('@settings-page-learn-more', 'href', 'https://docs.trypost.it/ai/introduction');
$page->click('@mcp-connect-claude');
- waitForMcpSettingsTestId($page, 'mcp-dialog-waiting');
+ waitFor($page, '@mcp-dialog-waiting');
$page->assertSeeIn('@mcp-dialog', 'Connect TryPost to Claude')
->assertSeeIn('@mcp-dialog-url', route('mcp.trypost'))
->keys('@mcp-dialog', 'Escape');
- waitForMcpSettingsTestIdGone($page, 'mcp-dialog');
+ waitForGone($page, '@mcp-dialog');
$page->click('@mcp-connect-other');
- waitForMcpSettingsTestId($page, 'mcp-dialog-config');
+ waitFor($page, '@mcp-dialog-config');
$page->assertSeeIn('@mcp-dialog', __('mcp.other_dialog_title'))
->assertVisible('@mcp-dialog-step-add')
@@ -173,21 +147,21 @@ test('a new connection closes the connect dialog and shows the connected tab', f
$this->actingAs($user->fresh());
$page = visit(route('app.mcp.index'));
- waitForMcpSettingsTestId($page, 'mcp-connected-empty-connect');
+ waitFor($page, '@mcp-connected-empty-connect');
$page->click('@mcp-connected-empty-connect');
- waitForMcpSettingsTestId($page, 'mcp-connect-chatgpt');
+ waitFor($page, '@mcp-connect-chatgpt');
$page->click('@mcp-connect-chatgpt');
- waitForMcpSettingsTestId($page, 'mcp-dialog-waiting');
+ waitFor($page, '@mcp-dialog-waiting');
$clientId = mcpOauthClient('ChatGPT');
mcpAccessToken($user, $clientId, $workspace);
- waitForMcpSettingsTestId($page, 'confetti-canvas');
+ waitFor($page, '@confetti-canvas');
$page->assertPresent('@confetti-canvas');
- waitForMcpSettingsTestId($page, "mcp-connected-client-{$clientId}");
- waitForMcpSettingsTestIdGone($page, 'mcp-dialog');
+ waitFor($page, "@mcp-connected-client-{$clientId}");
+ waitForGone($page, '@mcp-dialog');
$page->assertVisible("@mcp-connected-client-{$clientId}")
->assertNotPresent('@mcp-dialog')
diff --git a/tests/Browser/MediaEditorTest.php b/tests/Browser/MediaEditorTest.php
index 4881071c0..fe56615e1 100644
--- a/tests/Browser/MediaEditorTest.php
+++ b/tests/Browser/MediaEditorTest.php
@@ -51,26 +51,10 @@ function seedMediaEditorPost(ContentType $contentType = ContentType::InstagramFe
return [$post];
}
-/**
- * Polls from the page until `$condition` holds (never sleep(): the test server
- * only ticks while Pest awaits Playwright).
- */
-function waitForMediaEditor(mixed $page, string $condition): void
-{
- $page->script(<<<JS
- (async () => {
- for (let attempt = 0; attempt < 100; attempt++) {
- if ({$condition}) return;
- await new Promise((resolve) => setTimeout(resolve, 100));
- }
- })();
- JS);
-}
-
function openMediaEditor(mixed $page, string $accountId, int $index = 0): void
{
openMediaEditorPanel($page, $accountId, $index);
- waitForMediaEditor($page, "document.querySelector('[data-testid=\"media-editor-selection\"]')?.getBoundingClientRect().width > 0");
+ waitForState($page, '@media-editor-selection', 'element.getBoundingClientRect().width > 0');
}
/**
@@ -79,9 +63,9 @@ function openMediaEditor(mixed $page, string $accountId, int $index = 0): void
*/
function openMediaEditorPanel(mixed $page, string $accountId, int $index = 0): void
{
- waitForMediaEditor($page, "document.querySelector('[data-testid=\"composer-{$accountId}-edit-{$index}\"]')");
+ waitForState($page, "@composer-{$accountId}-edit-{$index}", 'true');
$page->click("@composer-{$accountId}-edit-{$index}");
- waitForMediaEditor($page, "document.querySelector('[data-testid=\"crop-aspect-freeform\"]')");
+ waitForState($page, '@crop-aspect-freeform', 'true');
}
/**
@@ -109,9 +93,10 @@ function clickMediaEditorStage(mixed $page, float $x, float $y): void
function saveMediaEditorDraft(mixed $page): void
{
- waitForMediaEditor($page, "!document.querySelector('[data-testid=\"media-editor\"]') && document.querySelector('[data-testid=\"composer-save-draft\"]')?.disabled === false");
+ waitForGone($page, '@media-editor');
+ waitForState($page, '@composer-save-draft', 'element.disabled === false');
$page->click('@composer-save-draft');
- waitForMediaEditor($page, "!document.querySelector('[data-testid=\"post-composer-dialog\"]')");
+ waitForGone($page, '@post-composer-dialog');
}
test('the media editor keeps its preview and controls separate at every viewport', function (int $width, int $height) {
@@ -303,7 +288,7 @@ test('alt text can be generated with AI for a post image', function () {
$page->click('@media-editor-alt-tab')
->click('@media-editor-alt-generate');
- waitForMediaEditor($page, "document.querySelector('[data-testid=\"media-editor-alt-text\"]')?.value.length > 0");
+ waitForState($page, '@media-editor-alt-text', 'element.value.length > 0');
expect($page->script('document.querySelector("[data-testid=media-editor-alt-text]").value'))
->toBe('Four coloured squares in a grid.');
@@ -331,13 +316,13 @@ test('center and reset only enable once the geometry changes', function () {
$page->click('@crop-aspect-freeform')
->drag('@media-editor-handle-nw', '@media-editor-stage');
- waitForMediaEditor($page, "document.querySelector('[data-testid=\"media-editor-center\"]').disabled === false");
+ waitForState($page, '@media-editor-center', 'element.disabled === false');
expect($isDisabled('media-editor-center'))->toBeFalse()
->and($isDisabled('media-editor-reset'))->toBeFalse();
$page->click('@media-editor-reset');
- waitForMediaEditor($page, "document.querySelector('[data-testid=\"media-editor-reset\"]').disabled === true");
+ waitForState($page, '@media-editor-reset', 'element.disabled === true');
expect($isDisabled('media-editor-center'))->toBeTrue()
->and($isDisabled('media-editor-reset'))->toBeTrue();
@@ -389,14 +374,14 @@ test('closing with the × discards edits like Cancel', function () {
$page->click('@media-editor-rotate-right')
->assertSee('Apply changes to 1 item')
->click('@media-editor-close');
- waitForMediaEditor($page, "!document.querySelector('[data-testid=\"media-editor\"]')");
+ waitForGone($page, '@media-editor');
$page->assertMissing('@media-editor');
openMediaEditor($page, $post->social_account_id);
$page->assertDisabled('@media-editor-apply')
->assertDisabled('@media-editor-reset')
->click('@media-editor-close');
- waitForMediaEditor($page, "!document.querySelector('[data-testid=\"media-editor\"]')");
+ waitForGone($page, '@media-editor');
expect($post->fresh()->media[0]['id'])->toBe('image-1');
$page->assertNoJavaScriptErrors();
@@ -435,14 +420,8 @@ function openMediaEditorComposer(User $user, array $accounts, array $files): mix
test()->actingAs($user);
$fixture = base64_encode((string) file_get_contents(base_path('tests/fixtures/crop-quadrants.png')));
$page = visit(route('app.posts.create'));
- waitForMediaEditor($page, <<<'JS'
- (() => {
- const sheet = document.querySelector('[data-testid="post-composer-dialog"]');
- return sheet?.getAttribute('data-state') === 'open'
- && sheet.getAnimations().every((animation) => animation.playState !== 'running')
- && document.querySelector('[data-testid="composer-add-account"]')?.getBoundingClientRect().height > 0;
- })()
- JS);
+ waitForOpen($page, '@post-composer-dialog');
+ waitFor($page, '@composer-add-account');
$page->fill('@composer-base-content', 'Editing shared media');
$encodedFiles = json_encode($files);
@@ -469,14 +448,15 @@ function openMediaEditorComposer(User $user, array $accounts, array $files): mix
})();
JS);
$count = count($files);
- waitForMediaEditor($page, "document.querySelectorAll('[data-testid=\"composer-media-item\"]').length === {$count} && !document.querySelector('[data-testid=\"composer-upload-item\"]')");
+ waitForCount($page, '@composer-media-item', $count);
+ waitForGone($page, '@composer-upload-item');
if ($accounts !== []) {
$page->click('@composer-add-account');
foreach ($accounts as $account) {
$page->click("@composer-account-option-{$account->id}");
}
$prefix = count($accounts) === 1 ? "composer-{$accounts[0]->id}" : 'composer';
- waitForMediaEditor($page, "document.querySelectorAll('[data-testid=\"{$prefix}-media-item\"]').length === {$count}");
+ waitForCount($page, "@{$prefix}-media-item", $count);
}
return $page;
@@ -549,7 +529,7 @@ test('the ALT button opens the editor on the Alt Text segment', function () {
$page = openMediaEditorComposer($user, [$instagram], [mediaEditorPng('photo.png')]);
$page->click("@composer-{$instagram->id}-alt-0");
- waitForMediaEditor($page, "document.querySelector('[data-testid=\"media-editor-alt-text\"]')");
+ waitForState($page, '@media-editor-alt-text', 'true');
expect($page->script("document.querySelector('[data-testid=\"media-editor-alt-tab\"]').getAttribute('aria-pressed')"))->toBe('true');
$page->assertVisible('@media-editor-alt-text')
@@ -561,13 +541,13 @@ test('the ALT button opens the editor on the Alt Text segment', function () {
*/
function applyMediaEditorAltText(mixed $page, string $prefix, string $altText): void
{
- waitForMediaEditor($page, "document.querySelector('[data-testid=\"{$prefix}-alt-0\"]')");
+ waitForState($page, "@{$prefix}-alt-0", 'true');
$page->click("@{$prefix}-alt-0");
- waitForMediaEditor($page, "document.querySelector('[data-testid=\"media-editor-alt-text\"]')");
+ waitForState($page, '@media-editor-alt-text', 'true');
$page->fill('@media-editor-alt-text', $altText);
- waitForMediaEditor($page, "document.querySelector('[data-testid=\"media-editor-apply\"]')?.disabled === false");
+ waitForState($page, '@media-editor-apply', 'element.disabled === false');
$page->click('@media-editor-apply');
- waitForMediaEditor($page, "!document.querySelector('[data-testid=\"media-editor\"]')");
+ waitForGone($page, '@media-editor');
}
/**
@@ -587,16 +567,16 @@ test('alt text is offered only once a channel is selected', function () {
expect(mediaEditorTileButtons($page, 'composer', 0))->toBe(['composer-remove-0', 'composer-edit-0']);
$page->click('@composer-edit-0');
- waitForMediaEditor($page, "document.querySelector('[data-testid=\"crop-aspect-freeform\"]')");
+ waitForState($page, '@crop-aspect-freeform', 'true');
$page->assertMissing('@media-editor-alt-tab')
->click('@media-editor-cancel');
- waitForMediaEditor($page, "!document.querySelector('[data-testid=\"media-editor\"]')");
+ waitForGone($page, '@media-editor');
if (! $page->script("Boolean(document.querySelector('[data-testid=\"composer-account-option-{$linkedin->id}\"]'))")) {
$page->click('@composer-add-account');
}
$page->click("@composer-account-option-{$linkedin->id}");
- waitForMediaEditor($page, "document.querySelector('[data-testid=\"composer-{$linkedin->id}-alt-0\"]')");
+ waitForState($page, "@composer-{$linkedin->id}-alt-0", 'true');
expect(mediaEditorTileButtons($page, "composer-{$linkedin->id}", 0))->toBe(["composer-{$linkedin->id}-remove-0", "composer-{$linkedin->id}-alt-0", "composer-{$linkedin->id}-edit-0"]);
$page->assertNoJavaScriptErrors();
@@ -629,9 +609,9 @@ test('a step 2 alt text stays on its channel and the others keep the shared one'
applyMediaEditorAltText($page, "composer-{$first->id}", 'First channel description');
$page->click("@composer-account-{$second->id}");
- waitForMediaEditor($page, "document.querySelector('[data-testid=\"composer-{$second->id}-alt-0\"]')");
+ waitForState($page, "@composer-{$second->id}-alt-0", 'true');
$page->click("@composer-{$second->id}-alt-0");
- waitForMediaEditor($page, "document.querySelector('[data-testid=\"media-editor-alt-text\"]')");
+ waitForState($page, '@media-editor-alt-text', 'true');
expect($page->script("document.querySelector('[data-testid=\"media-editor-alt-text\"]').value"))->toBe('Shared description');
$page->click('@media-editor-cancel');
saveMediaEditorDraft($page);
@@ -652,18 +632,19 @@ test('a step 1 edit replaces the shared item in place and every post owns its ow
$secondSrc = mediaEditorTileSrc($page, 'composer', 1);
$page->click('@composer-edit-1');
- waitForMediaEditor($page, "document.querySelector('[data-testid=\"media-editor-selection\"]')?.getBoundingClientRect().width > 0");
+ waitForState($page, '@media-editor-selection', 'element.getBoundingClientRect().width > 0');
$page->click('@media-editor-rotate-right');
- waitForMediaEditor($page, "document.querySelector('[data-testid=\"media-editor-apply\"]')?.disabled === false");
+ waitForState($page, '@media-editor-apply', 'element.disabled === false');
$page->click('@media-editor-apply');
- waitForMediaEditor($page, "!document.querySelector('[data-testid=\"media-editor\"]') && document.querySelector('[data-testid=\"composer-save-draft\"]')?.disabled === false");
+ waitForGone($page, '@media-editor');
+ waitForState($page, '@composer-save-draft', 'element.disabled === false');
expect(mediaEditorTileSrc($page, 'composer', 0))->toBe($firstSrc)
->and(mediaEditorTileSrc($page, 'composer', 1))->not->toBe($secondSrc)
->and(mediaEditorTileSrc($page, 'composer', 1))->not->toBeNull();
$page->click('@composer-save-draft');
- waitForMediaEditor($page, "!document.querySelector('[data-testid=\"post-composer-dialog\"]')");
+ waitForGone($page, '@post-composer-dialog');
$posts = Post::query()->whereIn('social_account_id', [$first->id, $second->id])->get();
expect($posts)->toHaveCount(2);
@@ -689,20 +670,21 @@ test('a step 2 edit replaces only that channel\'s item and leaves the shared lis
->click("@composer-account-{$first->id}");
openMediaEditor($page, $first->id);
$page->click('@media-editor-rotate-right');
- waitForMediaEditor($page, "document.querySelector('[data-testid=\"media-editor-apply\"]')?.disabled === false");
+ waitForState($page, '@media-editor-apply', 'element.disabled === false');
$page->click('@media-editor-apply');
- waitForMediaEditor($page, "!document.querySelector('[data-testid=\"media-editor\"]') && document.querySelector('[data-testid=\"composer-save-draft\"]')?.disabled === false");
+ waitForGone($page, '@media-editor');
+ waitForState($page, '@composer-save-draft', 'element.disabled === false');
expect(mediaEditorTileSrc($page, "composer-{$first->id}", 0))->not->toBe($sharedSrc);
$page->click("@composer-account-{$second->id}");
- waitForMediaEditor($page, "document.querySelector('[data-testid=\"composer-{$second->id}-media-item-0\"]')");
+ waitForState($page, "@composer-{$second->id}-media-item-0", 'true');
expect(mediaEditorTileSrc($page, "composer-{$second->id}", 0))->toBe($sharedSrc);
$page->click('@composer-back');
- waitForMediaEditor($page, "document.querySelector('[data-testid=\"composer-back-confirm-go\"]')");
+ waitForState($page, '@composer-back-confirm-go', 'true');
$page->click('@composer-back-confirm-go');
- waitForMediaEditor($page, "document.querySelector('[data-testid=\"composer-media-item-0\"]')");
+ waitForState($page, '@composer-media-item-0', 'true');
expect(mediaEditorTileSrc($page, 'composer', 0))->toBe($sharedSrc);
$page->assertNoJavaScriptErrors();
});
@@ -731,11 +713,13 @@ test('a failed edit upload shows the inline error and keeps the original tile',
JS);
$page->click("@composer-{$linkedin->id}-edit-0");
- waitForMediaEditor($page, "document.querySelector('[data-testid=\"media-editor-selection\"]')?.getBoundingClientRect().width > 0");
+ waitForState($page, '@media-editor-selection', 'element.getBoundingClientRect().width > 0');
$page->click('@media-editor-rotate-right');
- waitForMediaEditor($page, "document.querySelector('[data-testid=\"media-editor-apply\"]')?.disabled === false");
+ waitForState($page, '@media-editor-apply', 'element.disabled === false');
$page->click('@media-editor-apply');
- waitForMediaEditor($page, "window.__editUploadFailed && document.querySelector('[data-testid=\"composer-{$linkedin->id}-crop-error\"]') && document.querySelector('[data-testid=\"composer-save-draft\"]')?.disabled === false");
+ waitForCondition($page, 'window.__editUploadFailed');
+ waitForState($page, "@composer-{$linkedin->id}-crop-error", 'true');
+ waitForState($page, '@composer-save-draft', 'element.disabled === false');
expect($page->script('Boolean(window.__editUploadFailed)'))->toBeTrue()
->and(mediaEditorTileSrc($page, "composer-{$linkedin->id}", 0))->toBe($originalSrc)
@@ -768,9 +752,9 @@ test('a reel video gets a Thumbnail segment whose frame is saved as the cover of
[$post] = seedMediaEditorVideoPost(ContentType::InstagramReel);
$accountId = $post->social_account_id;
$page = visit(route('app.posts.edit', $post));
- waitForMediaEditor($page, "document.querySelector('[data-testid=\"composer-{$accountId}-edit-0\"]')");
+ waitForState($page, "@composer-{$accountId}-edit-0", 'true');
$page->click("@composer-{$accountId}-edit-0");
- waitForMediaEditor($page, "document.querySelector('[data-testid=\"media-editor-cover\"]')");
+ waitForState($page, '@media-editor-cover', 'true');
expect(mediaEditorSegmentIds($page))->toBe(['media-editor-thumbnail-tab'])
->and($page->script("document.querySelector('[data-testid=\"media-editor-thumbnail-tab\"]').getAttribute('aria-pressed')"))->toBe('true')
@@ -780,7 +764,7 @@ test('a reel video gets a Thumbnail segment whose frame is saved as the cover of
->assertSee('Choose a thumbnail')
->assertVisible('@media-editor-stage-video')
->assertAttribute('@media-editor-thumb-0', 'aria-label', 'Video 1');
- waitForMediaEditor($page, "document.querySelector('[data-testid=\"media-editor-cover\"]')?.max === '3'");
+ waitForState($page, '@media-editor-cover', "element.max === '3'");
expect($page->script("document.querySelector('[data-testid=\"media-editor-cover\"]').max"))->toBe('3');
$page->script(<<<'JS'
@@ -790,9 +774,9 @@ test('a reel video gets a Thumbnail segment whose frame is saved as the cover of
slider.dispatchEvent(new Event('input', { bubbles: true }));
})();
JS);
- waitForMediaEditor($page, "document.querySelector('[data-testid=\"media-editor-apply\"]')?.disabled === false");
+ waitForState($page, '@media-editor-apply', 'element.disabled === false');
- waitForMediaEditor($page, "Math.abs(document.querySelector('[data-testid=\"media-editor-stage-video\"]')?.currentTime - 2.5) < 0.01");
+ waitForState($page, '@media-editor-stage-video', 'Math.abs(element.currentTime - 2.5) < 0.01');
expect($page->script("document.querySelector('[data-testid=\"media-editor-cover-value\"]').textContent.trim()"))->toBe('0:02.5')
->and($page->script("document.querySelector('[data-testid=\"media-editor-cover\"]').getAttribute('aria-valuetext')"))->toBe('2.5 seconds')
@@ -810,7 +794,7 @@ test('a video on an X post shows no pencil', function () {
[$post] = seedMediaEditorVideoPost(ContentType::XPost);
$accountId = $post->social_account_id;
$page = visit(route('app.posts.edit', $post));
- waitForMediaEditor($page, "document.querySelector('[data-testid=\"composer-{$accountId}-media-item-0\"]')");
+ waitForState($page, "@composer-{$accountId}-media-item-0", 'true');
$page->assertPresent("@composer-{$accountId}-media-item-0")
->assertMissing("@composer-{$accountId}-edit-0")
@@ -823,11 +807,11 @@ test('only a freeform crop can be resized; a chosen ratio only moves', function
openMediaEditor($page, $post->social_account_id);
$page->click('@crop-aspect-4-5');
- waitForMediaEditor($page, "!document.querySelector('[data-testid=\"media-editor-handle-nw\"]')");
+ waitForGone($page, '@media-editor-handle-nw');
$page->assertMissing('@media-editor-handle-nw')
->assertPresent('@media-editor-selection')
->click('@crop-aspect-freeform');
- waitForMediaEditor($page, "document.querySelector('[data-testid=\"media-editor-handle-nw\"]')");
+ waitForState($page, '@media-editor-handle-nw', 'true');
$page->assertPresent('@media-editor-handle-nw')
->assertPresent('@media-editor-handle-se')
@@ -840,10 +824,10 @@ test('filter intensity shows for a filter, not for the original, and sliders fil
openMediaEditor($page, $post->social_account_id);
$page->click('@media-editor-appearance-section');
- waitForMediaEditor($page, "document.querySelector('[data-testid=\"media-filter-sepia\"]')");
+ waitForState($page, '@media-filter-sepia', 'true');
$page->assertMissing('@media-filter-intensity')
->click('@media-filter-sepia');
- waitForMediaEditor($page, "document.querySelector('[data-testid=\"media-filter-intensity\"]')");
+ waitForState($page, '@media-filter-intensity', 'true');
$page->script(<<<'JS'
(() => {
@@ -856,7 +840,7 @@ test('filter intensity shows for a filter, not for the original, and sliders fil
set('media-adjust-brightness', 60);
})()
JS);
- waitForMediaEditor($page, "document.querySelector('[data-testid=\"media-adjust-brightness\"]').style.getPropertyValue('--range-to').includes('0.8')");
+ waitForState($page, '@media-adjust-brightness', "element.style.getPropertyValue('--range-to').includes('0.8')");
expect($page->script(<<<'JS'
(() => {
@@ -873,7 +857,7 @@ test('filter intensity shows for a filter, not for the original, and sliders fil
]);
$page->click('@media-filter-original');
- waitForMediaEditor($page, "!document.querySelector('[data-testid=\"media-filter-intensity\"]')");
+ waitForGone($page, '@media-filter-intensity');
$page->assertMissing('@media-filter-intensity')
->assertNoJavaScriptErrors();
});
@@ -896,7 +880,7 @@ test('an image stored on another host is edited through the app, so applying wor
$page->click('@media-editor-rotate-right')
->click('@media-editor-apply');
- waitForMediaEditor($page, "!document.querySelector('[data-testid=\"media-editor\"]') || document.querySelector('[data-testid=\"media-editor-error\"]')");
+ waitForGoneOrShown($page, gone: '@media-editor', shown: '@media-editor-error');
$page->assertMissing('@media-editor-error')
->assertMissing('@media-editor');
@@ -924,7 +908,7 @@ test('the filter intensity reaches the saved pixels', function (int $intensity)
openMediaEditor($page, $post->social_account_id);
$page->click('@media-editor-appearance-section')->click('@media-filter-mono');
- waitForMediaEditor($page, "document.querySelector('[data-testid=\"media-filter-intensity\"]')");
+ waitForState($page, '@media-filter-intensity', 'true');
setMediaEditorRange($page, 'media-filter-intensity', $intensity);
$page->click('@media-editor-apply');
saveMediaEditorDraft($page);
diff --git a/tests/Browser/MediaLightboxTest.php b/tests/Browser/MediaLightboxTest.php
index f4b1281f0..b49d25559 100644
--- a/tests/Browser/MediaLightboxTest.php
+++ b/tests/Browser/MediaLightboxTest.php
@@ -12,28 +12,6 @@ use App\Models\Workspace;
use Illuminate\Support\Facades\Queue;
use Illuminate\Support\Str;
-function waitForMediaLightboxCondition(mixed $page, string $condition): void
-{
- $page->script(<<<JS
- (async () => {
- for (let attempt = 0; attempt < 100; attempt++) {
- if ({$condition}) return;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })();
- JS);
-}
-
-function waitForMediaLightboxTestId(mixed $page, string $testId): void
-{
- waitForMediaLightboxCondition($page, "document.querySelector('[data-testid=\"{$testId}\"]')?.getBoundingClientRect().height > 0");
-}
-
-function waitForMediaLightboxGone(mixed $page): void
-{
- waitForMediaLightboxCondition($page, "!document.querySelector('[data-testid=\"media-lightbox\"]')");
-}
-
function mediaLightboxCounter(mixed $page): string
{
return trim((string) $page->script("document.querySelector('[data-testid=\"media-lightbox-counter\"]')?.textContent ?? ''"));
@@ -108,11 +86,11 @@ test('a single image opens without navigation and closes on escape', function ()
$this->actingAs($user);
$page = visit(route('app.posts.index', ['tab' => 'drafts']));
- waitForMediaLightboxTestId($page, "post-thumbnail-{$post->id}-0");
+ waitFor($page, "@post-thumbnail-{$post->id}-0");
$before = $page->script('location.href');
$page->click("@post-thumbnail-{$post->id}-0");
- waitForMediaLightboxTestId($page, 'media-lightbox-image');
+ waitFor($page, '@media-lightbox-image');
$page->assertVisible('@media-lightbox-image')
->assertVisible('@media-lightbox-close')
@@ -125,7 +103,7 @@ test('a single image opens without navigation and closes on escape', function ()
->and(mediaLightboxImageLabel($page))->toBe('1');
$page->keys('@media-lightbox', 'Escape');
- waitForMediaLightboxGone($page);
+ waitForGone($page, '@media-lightbox');
$page->assertNotPresent('@media-lightbox');
expect($page->script('location.href'))->toBe($before);
@@ -137,7 +115,7 @@ test('five images open at the clicked one and move with the buttons and arrow ke
$this->actingAs($user);
$page = visit(route('app.posts.index', ['tab' => 'sent']));
- waitForMediaLightboxTestId($page, "post-thumbnail-{$post->id}-1");
+ waitFor($page, "@post-thumbnail-{$post->id}-1");
$page->assertPresent("@post-thumbnail-more-{$post->id}")
->assertNotPresent("@post-thumbnail-{$post->id}-4");
@@ -147,23 +125,23 @@ test('five images open at the clicked one and move with the buttons and arrow ke
expect($page->script($expandOpacity))->toBe('0');
$page->hover("@post-thumbnail-{$post->id}-1");
- waitForMediaLightboxCondition($page, "{$expandOpacity} === '1'");
+ waitForState($page, "@post-thumbnail-expand-{$post->id}-1", "getComputedStyle(element).opacity === '1'");
expect($page->script($expandOpacity))->toBe('1');
$page->click("@post-thumbnail-{$post->id}-1");
- waitForMediaLightboxTestId($page, 'media-lightbox-counter');
+ waitFor($page, '@media-lightbox-counter');
expect(mediaLightboxCounter($page))->toBe('2 / 5')
->and(mediaLightboxImageLabel($page))->toBe('2');
$page->click('@media-lightbox-next');
- waitForMediaLightboxCondition($page, "document.querySelector('[data-testid=\"media-lightbox-counter\"]').textContent.trim() === '3 / 5'");
+ waitForState($page, '@media-lightbox-counter', "element.textContent.trim() === '3 / 5'");
expect(mediaLightboxCounter($page))->toBe('3 / 5');
$page->keys('@media-lightbox', 'ArrowRight');
$page->keys('@media-lightbox', 'ArrowRight');
- waitForMediaLightboxCondition($page, "document.querySelector('[data-testid=\"media-lightbox-counter\"]').textContent.trim() === '5 / 5'");
+ waitForState($page, '@media-lightbox-counter', "element.textContent.trim() === '5 / 5'");
expect(mediaLightboxCounter($page))->toBe('5 / 5')
->and($page->script("document.querySelector('[data-testid=\"media-lightbox-next\"]').disabled"))->toBeTrue()
->and($page->script("document.querySelector('[data-testid=\"media-lightbox-previous\"]').disabled"))->toBeFalse();
@@ -172,19 +150,19 @@ test('five images open at the clicked one and move with the buttons and arrow ke
expect(mediaLightboxCounter($page))->toBe('5 / 5');
$page->click('@media-lightbox-previous');
- waitForMediaLightboxCondition($page, "document.querySelector('[data-testid=\"media-lightbox-counter\"]').textContent.trim() === '4 / 5'");
+ waitForState($page, '@media-lightbox-counter', "element.textContent.trim() === '4 / 5'");
$page->keys('@media-lightbox', 'ArrowLeft');
$page->keys('@media-lightbox', 'ArrowLeft');
$page->keys('@media-lightbox', 'ArrowLeft');
- waitForMediaLightboxCondition($page, "document.querySelector('[data-testid=\"media-lightbox-counter\"]').textContent.trim() === '1 / 5'");
+ waitForState($page, '@media-lightbox-counter', "element.textContent.trim() === '1 / 5'");
expect(mediaLightboxCounter($page))->toBe('1 / 5')
->and($page->script("document.querySelector('[data-testid=\"media-lightbox-previous\"]').disabled"))->toBeTrue();
$page->click('@media-lightbox-close');
- waitForMediaLightboxGone($page);
+ waitForGone($page, '@media-lightbox');
$page->click("@post-thumbnail-more-{$post->id}");
- waitForMediaLightboxTestId($page, 'media-lightbox-counter');
+ waitFor($page, '@media-lightbox-counter');
expect(mediaLightboxCounter($page))->toBe('5 / 5')
->and(mediaLightboxImageLabel($page))->toBe('5');
@@ -196,7 +174,7 @@ test('five images open at the clicked one and move with the buttons and arrow ke
->and($page->script($active))->toBe(['false', 'false', 'false', 'false', 'true']);
$page->click('@media-lightbox-thumbnail-3');
- waitForMediaLightboxCondition($page, "document.querySelector('[data-testid=\"media-lightbox-counter\"]').textContent.trim() === '4 / 5'");
+ waitForState($page, '@media-lightbox-counter', "element.textContent.trim() === '4 / 5'");
expect(mediaLightboxCounter($page))->toBe('4 / 5')
->and(mediaLightboxImageLabel($page))->toBe('4')
@@ -229,19 +207,19 @@ test('five images open at the clicked one and move with the buttons and arrow ke
$page->click('@media-lightbox-zoom-in');
$page->click('@media-lightbox-zoom-in');
- waitForMediaLightboxCondition($page, "{$scale} === 2");
+ waitForState($page, '@media-lightbox-image', 'new DOMMatrix(getComputedStyle(element).transform).a === 2');
expect($page->script($scale))->toEqual(2);
$page->click('@media-lightbox-zoom-in');
$page->click('@media-lightbox-zoom-in');
- waitForMediaLightboxCondition($page, "{$scale} === 3");
+ waitForState($page, '@media-lightbox-image', 'new DOMMatrix(getComputedStyle(element).transform).a === 3');
expect($page->script($scale))->toEqual(3)
->and($page->script("document.querySelector('[data-testid=\"media-lightbox-zoom-in\"]').disabled"))->toBeTrue();
$page->click('@media-lightbox-zoom-out');
- waitForMediaLightboxCondition($page, "{$scale} === 2.5");
+ waitForState($page, '@media-lightbox-image', 'new DOMMatrix(getComputedStyle(element).transform).a === 2.5');
expect($page->script($scale))->toEqual(2.5);
$page->assertVisible('@media-lightbox')
@@ -253,10 +231,10 @@ test('a video plays in the lightbox', function () {
$this->actingAs($user);
$page = visit(route('app.posts.index', ['tab' => 'sent']));
- waitForMediaLightboxTestId($page, "post-thumbnail-{$post->id}-1");
+ waitFor($page, "@post-thumbnail-{$post->id}-1");
$page->click("@post-thumbnail-{$post->id}-1");
- waitForMediaLightboxTestId($page, 'media-lightbox-counter');
+ waitFor($page, '@media-lightbox-counter');
expect(mediaLightboxCounter($page))->toBe('2 / 2')
->and($page->script("document.querySelector('[data-testid=\"media-lightbox-video\"]')?.tagName"))->toBe('VIDEO')
@@ -272,16 +250,16 @@ test('the details dialog media strip opens the same lightbox', function () {
$this->actingAs($user);
$page = visit(route('app.posts.index', ['post' => $post->id]));
- waitForMediaLightboxTestId($page, "post-details-media-item-{$post->id}-2");
+ waitFor($page, "@post-details-media-item-{$post->id}-2");
$page->click("@post-details-media-item-{$post->id}-2");
- waitForMediaLightboxTestId($page, 'media-lightbox-counter');
+ waitFor($page, '@media-lightbox-counter');
expect(mediaLightboxCounter($page))->toBe('3 / 3')
->and(mediaLightboxImageLabel($page))->toBe('3');
$page->keys('@media-lightbox', 'Escape');
- waitForMediaLightboxGone($page);
+ waitForGone($page, '@media-lightbox');
$page->assertNotPresent('@media-lightbox')
->assertVisible("@post-details-{$post->id}")
diff --git a/tests/Browser/MemberAccessDialogTest.php b/tests/Browser/MemberAccessDialogTest.php
index 4e1d1086e..b6e8a8bb2 100644
--- a/tests/Browser/MemberAccessDialogTest.php
+++ b/tests/Browser/MemberAccessDialogTest.php
@@ -6,30 +6,6 @@ use App\Models\Invite;
use App\Models\User;
use App\Models\Workspace;
-function waitForMemberAccessTestId(mixed $page, string $testId): void
-{
- $page->script(<<<JS
- (async () => {
- for (let attempt = 0; attempt < 100; attempt++) {
- if (document.querySelector('[data-testid="{$testId}"]')?.getBoundingClientRect().height > 0) return;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })();
- JS);
-}
-
-function waitForMemberAccessGone(mixed $page, string $testId): void
-{
- $page->script(<<<JS
- (async () => {
- for (let attempt = 0; attempt < 100; attempt++) {
- if (!document.querySelector('[data-testid="{$testId}"]')) return;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })();
- JS);
-}
-
/**
* @return array{0: User, 1: Workspace}
*/
@@ -49,27 +25,27 @@ test('the admin switch hides the publishing choice and the invite stores both fl
$this->actingAs($owner);
$page = visit(route('app.members'));
- waitForMemberAccessTestId($page, 'invite-member-button');
+ waitFor($page, '@invite-member-button');
$page->click('@invite-member-button');
- waitForMemberAccessTestId($page, 'member-access-publishing');
+ waitFor($page, '@member-access-publishing');
$page->assertScript('(() => { const row = document.querySelector("[data-testid=member-access-admin-row]").getBoundingClientRect(); const toggle = document.querySelector("[data-testid=member-access-admin]").getBoundingClientRect(); return Math.abs((row.top + row.bottom) / 2 - (toggle.top + toggle.bottom) / 2) < 1; })()', true);
$page->click('@member-access-admin');
- waitForMemberAccessGone($page, 'member-access-publishing');
+ waitForGone($page, '@member-access-publishing');
$page->assertMissing('@member-access-publishing')
->click('@member-access-admin');
- waitForMemberAccessTestId($page, 'member-access-publishing-trigger');
+ waitFor($page, '@member-access-publishing-trigger');
$page->click('@member-access-publishing-trigger');
- waitForMemberAccessTestId($page, 'member-access-publishing-approval');
+ waitFor($page, '@member-access-publishing-approval');
$page->click('@member-access-publishing-approval')
->fill('@invite-email', '[email protected]');
expect($page->script('document.querySelector("[data-testid=invite-member-cancel]").compareDocumentPosition(document.querySelector("[data-testid=invite-member-submit]")) & Node.DOCUMENT_POSITION_FOLLOWING'))->toBeGreaterThan(0);
$page->click('@invite-member-submit');
- waitForMemberAccessGone($page, 'invite-member-dialog');
+ waitForGone($page, '@invite-member-dialog');
$invite = Invite::query()->where('email', '[email protected]')->sole();
@@ -84,22 +60,22 @@ test('editing a member saves the publishing choice and labels the member', funct
$this->actingAs($owner);
$page = visit(route('app.members'));
- waitForMemberAccessTestId($page, "member-menu-{$member->id}");
+ waitFor($page, "@member-menu-{$member->id}");
$page->assertMissing("@member-menu-{$owner->id}")
->click("@member-menu-{$member->id}");
- waitForMemberAccessTestId($page, "member-edit-{$member->id}");
+ waitFor($page, "@member-edit-{$member->id}");
$page->click("@member-edit-{$member->id}");
- waitForMemberAccessTestId($page, 'member-access-publishing-trigger');
+ waitFor($page, '@member-access-publishing-trigger');
$page->assertSeeIn('@edit-member-dialog', 'Mia Member')
->click('@member-access-publishing-trigger');
- waitForMemberAccessTestId($page, 'member-access-publishing-approval');
+ waitFor($page, '@member-access-publishing-approval');
$page->click('@member-access-publishing-approval');
expect($page->script('document.querySelector("[data-testid=edit-member-cancel]").compareDocumentPosition(document.querySelector("[data-testid=edit-member-submit]")) & Node.DOCUMENT_POSITION_FOLLOWING'))->toBeGreaterThan(0);
$page->click('@edit-member-submit');
- waitForMemberAccessGone($page, 'edit-member-dialog');
+ waitForGone($page, '@edit-member-dialog');
$pivot = $workspace->members()->where('user_id', $member->id)->first()->pivot;
diff --git a/tests/Browser/MobileOverflowTest.php b/tests/Browser/MobileOverflowTest.php
index 652591c90..9e115dc39 100644
--- a/tests/Browser/MobileOverflowTest.php
+++ b/tests/Browser/MobileOverflowTest.php
@@ -18,12 +18,10 @@ use App\Models\Workspace;
*/
function assertNoHorizontalOverflow(mixed $page, string $label): void
{
+ waitForState($page, 'h1, h2, main, [data-sidebar="trigger"]', 'true');
+
$result = $page->script(<<<'JS'
(async () => {
- for (let i = 0; i < 80; i++) {
- if (document.querySelector('h1, h2, main, [data-sidebar="trigger"]')) break;
- await new Promise((r) => setTimeout(r, 50));
- }
await new Promise((r) => setTimeout(r, 400));
const vw = window.innerWidth;
let worst = null;
diff --git a/tests/Browser/NotificationPreferencesTest.php b/tests/Browser/NotificationPreferencesTest.php
index c8ea93dfa..e196a13c9 100644
--- a/tests/Browser/NotificationPreferencesTest.php
+++ b/tests/Browser/NotificationPreferencesTest.php
@@ -6,18 +6,6 @@ use App\Models\NotificationPreference;
use App\Models\User;
use App\Models\Workspace;
-function waitForNotificationPreferencesTestId(mixed $page, string $testId): void
-{
- $page->script(<<<JS
- (async () => {
- for (let attempt = 0; attempt < 100; attempt++) {
- if (document.querySelector('[data-testid="{$testId}"]')?.getBoundingClientRect().height > 0) return;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })();
- JS);
-}
-
function notificationPreferencesUser(): User
{
$user = User::factory()->create();
@@ -33,17 +21,17 @@ test('a switch saves on its own, survives a reload, and there is no save button'
$this->actingAs($user);
$page = visit(route('app.notifications.preferences'));
- waitForNotificationPreferencesTestId($page, 'notifications-post_failed');
+ waitFor($page, '@notifications-post_failed');
expect($page->script('document.querySelectorAll(\'[data-testid="notifications-page"] button:not([role="switch"])\').length'))->toBe(0);
$page->click('@notifications-post_failed');
- waitForNotificationPreferencesTestId($page, 'notifications-saved-post_failed');
+ waitFor($page, '@notifications-saved-post_failed');
expect(NotificationPreference::query()->where('user_id', $user->id)->sole()->post_failed)->toBeFalse();
$page = visit(route('app.notifications.preferences'));
- waitForNotificationPreferencesTestId($page, 'notifications-post_failed');
+ waitFor($page, '@notifications-post_failed');
$page->assertAttribute('@notifications-post_failed', 'data-state', 'unchecked')
->assertAttribute('@notifications-post_published', 'data-state', 'checked')
->assertNoJavaScriptErrors();
@@ -54,12 +42,12 @@ test('two switches toggled quickly both persist', function () {
$this->actingAs($user);
$page = visit(route('app.notifications.preferences'));
- waitForNotificationPreferencesTestId($page, 'notifications-collaboration');
+ waitFor($page, '@notifications-collaboration');
$page->script(<<<'JS'
document.querySelector('[data-testid="notifications-post_published"]').click();
document.querySelector('[data-testid="notifications-collaboration"]').click();
JS);
- waitForNotificationPreferencesTestId($page, 'notifications-saved-collaboration');
+ waitFor($page, '@notifications-saved-collaboration');
$preference = NotificationPreference::query()->where('user_id', $user->id)->sole();
expect($preference->post_published)->toBeFalse()
diff --git a/tests/Browser/PostApprovalsTest.php b/tests/Browser/PostApprovalsTest.php
index d873fd677..9a64694fc 100644
--- a/tests/Browser/PostApprovalsTest.php
+++ b/tests/Browser/PostApprovalsTest.php
@@ -15,30 +15,6 @@ use App\Support\PostingSchedule;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\Queue;
-function waitForApprovalsTestId(mixed $page, string $testId): void
-{
- $page->script(<<<JS
- (async () => {
- for (let attempt = 0; attempt < 100; attempt++) {
- if (document.querySelector('[data-testid="{$testId}"]')?.getBoundingClientRect().height > 0) return;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })();
- JS);
-}
-
-function waitForApprovalsGone(mixed $page, string $testId): void
-{
- $page->script(<<<JS
- (async () => {
- for (let attempt = 0; attempt < 100; attempt++) {
- if (!document.querySelector('[data-testid="{$testId}"]')) return;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })();
- JS);
-}
-
/**
* @return array{0: User, 1: Workspace, 2: SocialAccount, 3: User}
*/
@@ -96,7 +72,7 @@ test('an approver adds a queue request to the queue and rejects another', functi
$this->actingAs($owner);
$page = visit(route('app.posts.index', ['tab' => 'approvals']));
- waitForApprovalsTestId($page, "post-approve-{$queued->id}");
+ waitFor($page, "@post-approve-{$queued->id}");
$page->assertSeeIn('@publish-tab-count-approvals', '2')
->assertMissing("@post-approval-badge-{$queued->id}")
@@ -104,10 +80,10 @@ test('an approver adds a queue request to the queue and rejects another', functi
->assertSeeIn("@post-approve-{$queued->id}", 'Add to queue')
->assertSeeIn("@post-approve-{$timed->id}", 'Schedule')
->click("@post-approve-{$queued->id}");
- waitForApprovalsGone($page, "post-card-{$queued->id}");
+ waitForGone($page, "@post-card-{$queued->id}");
$page->click("@post-reject-{$timed->id}");
- waitForApprovalsGone($page, "post-card-{$timed->id}");
+ waitForGone($page, "@post-card-{$timed->id}");
expect($queued->fresh()->status)->toBe(PostStatus::Scheduled)
->and($queued->fresh()->approved_by)->toBe($owner->id)
@@ -128,15 +104,15 @@ test('a request whose time has passed asks for a new time or publish now', funct
$this->actingAs($owner);
$page = visit(route('app.posts.index', ['tab' => 'approvals']));
- waitForApprovalsTestId($page, "post-time-passed-{$late->id}");
+ waitFor($page, "@post-time-passed-{$late->id}");
$page->assertSeeIn("@post-approve-{$late->id}", 'Approve')
->click("@post-approve-{$late->id}");
- waitForApprovalsTestId($page, "post-approve-publish-now-{$late->id}");
+ waitFor($page, "@post-approve-publish-now-{$late->id}");
$page->assertVisible("@post-approve-picker-{$late->id}")
->click("@post-approve-publish-now-{$late->id}");
- waitForApprovalsGone($page, "post-card-{$late->id}");
+ waitForGone($page, "@post-card-{$late->id}");
expect($late->fresh()->status)->toBe(PostStatus::Publishing);
$page->assertNoJavaScriptErrors();
@@ -149,14 +125,14 @@ test('a requester sees only their own requests and can revert them', function ()
$this->actingAs($requester);
$page = visit(route('app.posts.index', ['tab' => 'approvals']));
- waitForApprovalsTestId($page, "post-revert-{$own->id}");
+ waitFor($page, "@post-revert-{$own->id}");
$page->assertSeeIn('@publish-tab-count-approvals', '1')
->assertMissing("@post-card-{$others->id}")
->assertMissing("@post-approve-{$own->id}")
->assertMissing("@post-reject-{$own->id}")
->click("@post-revert-{$own->id}");
- waitForApprovalsGone($page, "post-card-{$own->id}");
+ waitForGone($page, "@post-card-{$own->id}");
expect($own->fresh()->status)->toBe(PostStatus::Draft);
$page->assertNoJavaScriptErrors();
@@ -168,10 +144,10 @@ test('a requester adding a draft to the queue is told it awaits approval', funct
$this->actingAs($requester);
$page = visit(route('app.posts.index', ['tab' => 'drafts']));
- waitForApprovalsTestId($page, "post-add-to-queue-{$draft->id}");
+ waitFor($page, "@post-add-to-queue-{$draft->id}");
$page->click("@post-add-to-queue-{$draft->id}");
- waitForApprovalsTestId($page, 'post-schedule-toast');
+ waitFor($page, '@post-schedule-toast');
$page->assertSeeIn('@post-schedule-toast', 'Approval requested')
->assertDontSee('Added to queue')
@@ -191,9 +167,9 @@ test('a new time for a late request is typed in the channel zone', function () {
$this->actingAs($owner);
$page = visit(route('app.posts.index', ['tab' => 'approvals']));
- waitForApprovalsTestId($page, "post-approve-{$late->id}");
+ waitFor($page, "@post-approve-{$late->id}");
$page->click("@post-approve-{$late->id}");
- waitForApprovalsTestId($page, 'composer-schedule-timezone');
+ waitFor($page, '@composer-schedule-timezone');
expect(trim((string) $page->script('document.querySelector("[data-testid=composer-schedule-timezone]").textContent')))->toBe('America/Sao Paulo');
@@ -208,7 +184,7 @@ test('a new time for a late request is typed in the channel zone', function () {
$page->click("@composer-schedule-day-{$day}")
->fill('@composer-schedule-time-input', '1000')
->click('@composer-schedule-done');
- waitForApprovalsGone($page, "post-card-{$late->id}");
+ waitForGone($page, "@post-card-{$late->id}");
expect($late->fresh()->scheduled_at->toIso8601String())
->toBe(CarbonImmutable::parse("{$day} 10:00", 'America/Sao_Paulo')->utc()->toIso8601String());
diff --git a/tests/Browser/PostCardFooterTest.php b/tests/Browser/PostCardFooterTest.php
index 6f6ff39e2..05fe89ba6 100644
--- a/tests/Browser/PostCardFooterTest.php
+++ b/tests/Browser/PostCardFooterTest.php
@@ -7,19 +7,6 @@ use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
-function waitForPostCardFooterTestId(mixed $page, string $testId): void
-{
- $page->script(<<<JS
- (async () => {
- for (let attempt = 0; attempt < 200; attempt++) {
- const element = document.querySelector('[data-testid="{$testId}"]');
- if (element && element.getBoundingClientRect().height > 0) return;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })();
- JS);
-}
-
test('a post card footer sits in a rounded muted panel and a draft drops its status on the drafts tab', function () {
$user = User::factory()->create(['timezone' => 'UTC']);
$workspace = Workspace::factory()->create(['account_id' => $user->account_id, 'user_id' => $user->id]);
@@ -31,7 +18,7 @@ test('a post card footer sits in a rounded muted panel and a draft drops its sta
$this->actingAs($user);
$page = visit(route('app.posts.index', ['tab' => 'drafts']))->resize(1440, 900);
- waitForPostCardFooterTestId($page, "post-footer-{$draft->id}");
+ waitFor($page, "@post-footer-{$draft->id}");
expect($page->script(<<<JS
(() => {
diff --git a/tests/Browser/PostCardLabelsTest.php b/tests/Browser/PostCardLabelsTest.php
index 8df20e3dc..f0366ad92 100644
--- a/tests/Browser/PostCardLabelsTest.php
+++ b/tests/Browser/PostCardLabelsTest.php
@@ -18,13 +18,7 @@ function waitForCardLabelsStored(mixed $page, Post $post, array $expected): void
{
sort($expected);
- for ($attempt = 0; $attempt < 50; $attempt++) {
- if ($post->labels()->pluck('workspace_labels.id')->sort()->values()->all() === $expected) {
- return;
- }
-
- $page->script('new Promise((resolve) => setTimeout(resolve, 100))');
- }
+ waitForDatabase($page, fn () => $post->labels()->pluck('workspace_labels.id')->sort()->values()->all() === $expected);
}
/**
diff --git a/tests/Browser/PostComposerDialogTest.php b/tests/Browser/PostComposerDialogTest.php
index 1b59eef27..fbaf98df6 100644
--- a/tests/Browser/PostComposerDialogTest.php
+++ b/tests/Browser/PostComposerDialogTest.php
@@ -16,49 +16,23 @@ use App\Models\WorkspaceLabel;
use App\Models\WorkspaceSignature;
use Illuminate\Support\Facades\Storage;
-/**
- * The composer opens as an animated dialog; a click that lands before the
- * animation settles is swallowed. Poll from the page (never sleep()) until the
- * dialog is open and still.
- */
-function waitForComposerCondition(mixed $page, string $condition): void
-{
- $page->script(<<<JS
- (async () => {
- for (let attempt = 0; attempt < 300; attempt++) {
- if ({$condition}) return;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })();
- JS);
-}
-
function waitForComposerReady(mixed $page, string $testId = 'composer-add-account'): void
{
- $page->script(<<<JS
- (async () => {
- for (let attempt = 0; attempt < 300; attempt++) {
- const sheet = document.querySelector('[data-testid="post-composer-dialog"]');
- if (sheet?.getAttribute('data-state') === 'open'
- && sheet.getAnimations().every((animation) => animation.playState !== 'running')
- && document.querySelector('[data-testid="{$testId}"]')?.getBoundingClientRect().height > 0) return;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })();
- JS);
+ waitForOpen($page, '@post-composer-dialog');
+ waitFor($page, "@{$testId}");
}
function clickComposerDialogNewPost(mixed $page): void
{
$item = "document.querySelector('[data-testid=\"sidebar-new-post\"]')?.getBoundingClientRect().height > 0";
- $settled = "{$item} && document.querySelector('[data-testid=\"sidebar-new-menu\"]').getAnimations().every((animation) => animation.playState !== 'running')";
for ($attempt = 0; $attempt < 3 && ! $page->script("Boolean({$item})"); $attempt++) {
clickComposerDialogControl($page, '[data-testid="sidebar-new"]');
- waitForComposerCondition($page, $item);
+ waitFor($page, '@sidebar-new-post');
}
- waitForComposerCondition($page, $settled);
+ waitFor($page, '@sidebar-new-post');
+ waitForState($page, '@sidebar-new-menu', "element.getAnimations().every((animation) => animation.playState !== 'running')");
clickComposerDialogControl($page, '[data-testid="sidebar-new-post"]');
}
@@ -150,11 +124,11 @@ test('posts channel filter keeps accounts distinct and persists across tabs', fu
$this->actingAs($user);
$page = visit(route('app.posts.index', ['tab' => 'drafts']));
- waitForComposerCondition($page, "document.querySelector('[data-testid=\"post-card-{$firstPost->id}\"]')?.getBoundingClientRect().height > 0");
+ waitFor($page, "@post-card-{$firstPost->id}");
for ($attempt = 0; $attempt < 3 && ! $page->script("document.querySelector('[data-testid=\"posts-channel-search\"]')?.getBoundingClientRect().height > 0"); $attempt++) {
$page->click('@posts-channel-filter');
- waitForComposerCondition($page, "document.querySelector('[data-testid=\"posts-channel-search\"]')?.getBoundingClientRect().height > 0");
+ waitFor($page, '@posts-channel-search');
}
$page->fill('@posts-channel-search', 'SECOND instagram')
@@ -510,9 +484,9 @@ test('composer searches and selects multiple labels and exposes emoji and signat
->assertAttribute("@composer-label-checkbox-{$secondLabel->id}", 'data-state', 'checked');
$page->click('@composer-tags-trigger');
- waitForComposerCondition($page, "!document.querySelector('[data-testid=\"composer-label-search\"]')");
+ waitForGone($page, '@composer-label-search');
$page->click('@composer-base-emoji');
- waitForComposerCondition($page, "document.querySelector('button[aria-label=\"grinning face\"]')?.getBoundingClientRect().height > 0");
+ waitFor($page, 'button[aria-label="grinning face"]');
clickComposerDialogControl($page, 'button[aria-label="grinning face"]');
$page->assertValue('@composer-base-content', '😀')
->click('@composer-base-signature')
@@ -521,21 +495,14 @@ test('composer searches and selects multiple labels and exposes emoji and signat
->click('@composer-add-account')
->click("@composer-account-option-{$account->id}")
->assertVisible("@composer-{$account->id}-toolbar");
- waitForComposerCondition($page, "!document.querySelector('[data-testid=\"composer-account-option-{$account->id}\"]')");
+ waitForGone($page, "@composer-account-option-{$account->id}");
$page->click("@composer-{$account->id}-emoji");
- waitForComposerCondition($page, "document.querySelector('button[aria-label=\"grinning face with big eyes\"]')?.getBoundingClientRect().height > 0");
+ waitFor($page, 'button[aria-label="grinning face with big eyes"]');
clickComposerDialogControl($page, 'button[aria-label="grinning face with big eyes"]');
$page->assertValue("@composer-caption-{$account->id}", "😀\n\n#campaign😃")
->click('@composer-save-draft');
- $page->script(<<<'JS'
- (async () => {
- for (let attempt = 0; attempt < 300; attempt++) {
- if (!document.querySelector('[data-testid="post-composer-dialog"]')) return;
- await new Promise((resolve) => setTimeout(resolve, 100));
- }
- })();
- JS);
+ waitForGone($page, '@post-composer-dialog');
expect(Post::where('workspace_id', $workspace->id)->sole()->labels()->pluck('workspace_labels.id')->all())
->toHaveCount(2)
@@ -716,14 +683,7 @@ test('creating a four account draft keeps composition in the browser until save'
expect(Post::where('workspace_id', $workspace->id)->count())->toBe(0);
$page->click('@composer-save-draft');
- $page->script(<<<'JS'
- (async () => {
- for (let attempt = 0; attempt < 300; attempt++) {
- if (!document.querySelector('[data-testid="post-composer-dialog"]')) return;
- await new Promise((resolve) => setTimeout(resolve, 100));
- }
- })();
- JS);
+ waitForGone($page, '@post-composer-dialog');
expect(Post::where('workspace_id', $workspace->id)->count())->toBe(4);
expect(Post::where('workspace_id', $workspace->id)->pluck('content')->all())
@@ -780,15 +740,7 @@ test('create another reopens a fresh composer after saving a draft', function ()
->click('@composer-create-another')
->click('@composer-save-draft');
- $page->script(<<<'JS'
- (async () => {
- for (let attempt = 0; attempt < 300; attempt++) {
- const composer = document.querySelector('[data-testid="composer-base-content"]');
- if (composer && composer.value === '') return;
- await new Promise((resolve) => setTimeout(resolve, 100));
- }
- })();
- JS);
+ waitForState($page, '@composer-base-content', "element.value === ''");
$page->assertVisible('@post-composer-dialog')
->assertValue('@composer-base-content', '');
@@ -843,14 +795,7 @@ test('recovering an empty-target draft retains its caption media and labels', fu
->click('@composer-add-account')->click("@composer-account-option-{$account->id}")
->assertValue("@composer-caption-{$account->id}", 'Keep this draft')
->click('@composer-save-draft');
- $page->script(<<<'JS'
- (async () => {
- for (let attempt = 0; attempt < 300; attempt++) {
- if (!document.querySelector('[data-testid="post-composer-dialog"]')) return;
- await new Promise((resolve) => setTimeout(resolve, 100));
- }
- })();
- JS);
+ waitForGone($page, '@post-composer-dialog');
$recovered = Post::where('workspace_id', $workspace->id)->sole();
$owned = $recovered->ownedMedia()->sole();
@@ -896,7 +841,7 @@ test('post notes open after creation while the edit dialog still has its AI assi
$page = visit(route('app.posts.index', ['notes' => $post->id, 'note' => $note->id]));
$page->assertVisible("@post-notes-trigger-{$post->id}")
->assertSee('Please review the opening line');
- waitForComposerCondition($page, "document.querySelector('[data-note-id=\"{$note->id}\"]')?.classList.contains('bg-primary-subtle')");
+ waitForState($page, "[data-note-id=\"{$note->id}\"]", "element.classList.contains('bg-primary-subtle')");
$page->assertScript("document.querySelector('[data-note-id=\"{$note->id}\"]').classList.contains('bg-primary-subtle')", true);
expect($page->script("document.querySelector('[data-testid=\"post-notes-trigger-{$post->id}\"]').textContent.replace(/\\s+/g, ' ').trim()"))->toBe(__('notes.title').' 1');
@@ -1009,19 +954,16 @@ test('selecting a new image uploads an asset before any post is saved', function
$base64 = base64_encode((string) file_get_contents(base_path('tests/fixtures/crop-quadrants.png')));
$page->script(<<<JS
- (async () => {
+ (() => {
const input = document.querySelector('[data-testid="composer-{$account->id}-file-input"]');
const bytes = Uint8Array.from(atob('{$base64}'), (character) => character.charCodeAt(0));
const transfer = new DataTransfer();
transfer.items.add(new File([bytes], 'new-composer-image.png', { type: 'image/png' }));
input.files = transfer.files;
input.dispatchEvent(new Event('change', { bubbles: true }));
- for (let attempt = 0; attempt < 300; attempt++) {
- if (document.querySelector('[data-testid="composer-{$account->id}-media-item"]')) return;
- await new Promise((resolve) => setTimeout(resolve, 100));
- }
})();
JS);
+ waitForState($page, "@composer-{$account->id}-media-item", 'true');
$page->assertVisible("@composer-{$account->id}-media-item");
expect(Media::where('workspace_id', $workspace->id)->where('collection', Media::COLLECTION_UPLOADS)->count())->toBe(1)
@@ -1046,19 +988,16 @@ test('dropping an image into the composer uploads it without saving a post', fun
$base64 = base64_encode((string) file_get_contents(base_path('tests/fixtures/crop-quadrants.png')));
$page->script(<<<JS
- (async () => {
+ (() => {
const bytes = Uint8Array.from(atob('{$base64}'), (character) => character.charCodeAt(0));
const transfer = new DataTransfer();
transfer.items.add(new File([bytes], 'dropped-image.png', { type: 'image/png' }));
document.querySelector('[data-testid="composer-customization"]').dispatchEvent(
new DragEvent('drop', { bubbles: true, cancelable: true, dataTransfer: transfer }),
);
- for (let attempt = 0; attempt < 300; attempt++) {
- if (document.querySelectorAll('[data-testid="composer-{$account->id}-media-item"]').length === 1) return;
- await new Promise((resolve) => setTimeout(resolve, 100));
- }
})();
JS);
+ waitForCount($page, "@composer-{$account->id}-media-item", 1);
$page->assertVisible("@composer-{$account->id}-media-item");
expect(Media::where('workspace_id', $workspace->id)->where('collection', Media::COLLECTION_UPLOADS)->count())->toBe(1)
@@ -1083,19 +1022,16 @@ test('cropping in one network card creates a separate asset and leaves the other
$base64 = base64_encode((string) file_get_contents(base_path('tests/fixtures/crop-quadrants.png')));
$page->script(<<<JS
- (async () => {
+ (() => {
const input = document.querySelector('[data-testid="composer-file-input"]');
const bytes = Uint8Array.from(atob('{$base64}'), (character) => character.charCodeAt(0));
const transfer = new DataTransfer();
transfer.items.add(new File([bytes], 'crop-for-channel.png', { type: 'image/png' }));
input.files = transfer.files;
input.dispatchEvent(new Event('change', { bubbles: true }));
- for (let attempt = 0; attempt < 300; attempt++) {
- if (document.querySelector('[data-testid="composer-media-item"]')) return;
- await new Promise((resolve) => setTimeout(resolve, 100));
- }
})();
JS);
+ waitForState($page, '@composer-media-item', 'true');
$page->click('@composer-add-account');
foreach ($accounts as $account) {
@@ -1124,15 +1060,8 @@ test('cropping in one network card creates a separate asset and leaves the other
->click('@crop-aspect-1-1')
->click('@media-editor-apply');
- $page->script(<<<'JS'
- (async () => {
- for (let attempt = 0; attempt < 300; attempt++) {
- const save = document.querySelector('[data-testid="composer-save-draft"]');
- if (save && !save.disabled && !document.querySelector('[data-testid="media-editor-apply"]')) return;
- await new Promise((resolve) => setTimeout(resolve, 100));
- }
- })();
- JS);
+ waitForGone($page, '@media-editor-apply');
+ waitForState($page, '@composer-save-draft', '!element.disabled');
$page->click('@composer-save-draft');
$posts = Post::where('workspace_id', $workspace->id)->get()->keyBy('social_account_id');
@@ -1182,19 +1111,16 @@ test('video thumbnails appear in shared and channel media', function () {
waitForComposerReady($page);
$video = base64_encode((string) file_get_contents(base_path('tests/fixtures/sample.mp4')));
$page->script(<<<JS
- (async () => {
+ (() => {
const input = document.querySelector('[data-testid="composer-file-input"]');
const bytes = Uint8Array.from(atob('{$video}'), (character) => character.charCodeAt(0));
const transfer = new DataTransfer();
transfer.items.add(new File([bytes], 'sample.mp4', { type: 'video/mp4' }));
input.files = transfer.files;
input.dispatchEvent(new Event('change', { bubbles: true }));
- for (let attempt = 0; attempt < 300; attempt++) {
- if (document.querySelector('[data-testid="composer-media-item"] video')) return;
- await new Promise((resolve) => setTimeout(resolve, 100));
- }
})();
JS);
+ waitForState($page, '@composer-media-item video', 'true');
$source = $page->script('document.querySelector("[data-testid=composer-media-item] video")?.getAttribute("src")');
expect($source)->toBeString()->not->toBeEmpty();
@@ -1249,14 +1175,8 @@ test('failed crop upload keeps the original asset selected', function () {
$page->click("@composer-{$account->id}-edit-0")
->click('@crop-aspect-1-1')
->click('@media-editor-apply');
- $page->script(<<<'JS'
- (async () => {
- for (let attempt = 0; attempt < 300; attempt++) {
- if (window.__cropUploadFailed && document.querySelector('[data-testid="composer-save-draft"]')?.disabled === false) return;
- await new Promise((resolve) => setTimeout(resolve, 100));
- }
- })();
- JS);
+ waitForCondition($page, 'window.__cropUploadFailed');
+ waitForState($page, '@composer-save-draft', 'element.disabled === false');
expect($page->script('Boolean(window.__cropUploadFailed)'))->toBeTrue();
$page->click('@composer-save-draft');
@@ -1433,7 +1353,7 @@ test('select all picks only the channels the search shows, and the last used sho
->keys('@composer-account-search', 'Escape')
->fill("@composer-caption-{$instagram->id}", 'First post')
->click('@composer-save-draft');
- waitForComposerCondition($page, "!document.querySelector('[data-testid=\"post-composer-dialog\"]')");
+ waitForGone($page, '@post-composer-dialog');
waitForComposerReady($page, 'posts-new-post');
$page->click('@posts-new-post');
diff --git a/tests/Browser/PostDetailsDialogTest.php b/tests/Browser/PostDetailsDialogTest.php
index 6ab627bec..e1f0bd36f 100644
--- a/tests/Browser/PostDetailsDialogTest.php
+++ b/tests/Browser/PostDetailsDialogTest.php
@@ -17,23 +17,6 @@ use App\Models\Workspace;
use Illuminate\Support\Facades\Queue;
use Illuminate\Support\Str;
-function waitForPostDetailsDialogCondition(mixed $page, string $condition): void
-{
- $page->script(<<<JS
- (async () => {
- for (let attempt = 0; attempt < 100; attempt++) {
- if ({$condition}) return;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })();
- JS);
-}
-
-function waitForPostDetailsDialogTestId(mixed $page, string $testId): void
-{
- waitForPostDetailsDialogCondition($page, "document.querySelector('[data-testid=\"{$testId}\"]')?.getBoundingClientRect().height > 0");
-}
-
/**
* @return array{0: User, 1: SocialAccount}
*/
@@ -103,22 +86,22 @@ test('clicking a sent card opens the post details, and so does the menu', functi
$this->actingAs($user);
$page = visit(route('app.posts.index', ['tab' => 'sent']));
- waitForPostDetailsDialogTestId($page, "post-open-{$post->id}");
+ waitFor($page, "@post-open-{$post->id}");
$before = $page->script('location.href');
$page->click("@post-open-{$post->id}");
- waitForPostDetailsDialogTestId($page, "post-details-{$post->id}");
+ waitFor($page, "@post-details-{$post->id}");
expect($page->script('location.href'))->toBe($before);
$page->assertPresent("@post-details-status-{$post->id}")
->assertSeeIn("@post-details-text-{$post->id}", 'Details dialog post');
$page->keys("@post-details-{$post->id}", 'Escape');
- waitForPostDetailsDialogCondition($page, "!document.querySelector('[data-testid=\"post-details-{$post->id}\"]')");
+ waitForGone($page, "@post-details-{$post->id}");
$page->click("@post-card-menu-{$post->id}");
- waitForPostDetailsDialogTestId($page, "post-details-open-{$post->id}");
+ waitFor($page, "@post-details-open-{$post->id}");
$page->click("@post-details-open-{$post->id}");
- waitForPostDetailsDialogTestId($page, "post-details-{$post->id}");
+ waitFor($page, "@post-details-{$post->id}");
$page->assertNoJavaScriptErrors();
});
@@ -129,7 +112,7 @@ test('the post details deep link opens the dialog on the sent tab', function ()
$this->actingAs($user);
$page = visit(route('app.posts.index', ['post' => $post->id]));
- waitForPostDetailsDialogTestId($page, "post-details-{$post->id}");
+ waitFor($page, "@post-details-{$post->id}");
$page->assertVisible("@post-details-{$post->id}")
->assertSeeIn("@post-details-status-{$post->id}", __('posts.status.published'))
@@ -144,7 +127,7 @@ test('the post details of a google business post in review say google is reviewi
$this->actingAs($user);
$page = visit(route('app.posts.index', ['post' => $post->id]));
- waitForPostDetailsDialogTestId($page, "post-details-{$post->id}");
+ waitFor($page, "@post-details-{$post->id}");
$page->assertSeeIn("@post-details-status-{$post->id}", __('posts.publish.in_google_review'))
->assertNoJavaScriptErrors();
@@ -156,8 +139,8 @@ test('the details media sits below the text in a single scrollable row', functio
$this->actingAs($user);
$page = visit(route('app.posts.index', ['post' => $post->id]))->resize(1280, 900);
- waitForPostDetailsDialogTestId($page, "post-details-media-{$post->id}");
- waitForPostDetailsDialogCondition($page, "document.getAnimations().every((animation) => animation.playState !== 'running')");
+ waitFor($page, "@post-details-media-{$post->id}");
+ waitForCondition($page, "document.getAnimations().every((animation) => animation.playState !== 'running')");
$layout = $page->script(<<<JS
(() => {
@@ -200,9 +183,9 @@ test('the details metrics band scrolls with arrows, shows when it refreshed and
$this->actingAs($user);
$page = visit(route('app.posts.index', ['post' => $post->id]))->resize(390, 844);
- waitForPostDetailsDialogTestId($page, $band);
- waitForPostDetailsDialogCondition($page, "document.getAnimations().every((animation) => animation.playState !== 'running')");
- waitForPostDetailsDialogTestId($page, "{$band}-next");
+ waitFor($page, "@{$band}");
+ waitForCondition($page, "document.getAnimations().every((animation) => animation.playState !== 'running')");
+ waitFor($page, "@{$band}-next");
$page->assertVisible("@{$band}-next")
->assertPresent("@{$band}-fade-next")
@@ -211,17 +194,17 @@ test('the details metrics band scrolls with arrows, shows when it refreshed and
->assertMissing("@{$band}-refreshed");
$page->click("@{$band}-next");
- waitForPostDetailsDialogTestId($page, "{$band}-prev");
+ waitFor($page, "@{$band}-prev");
$page->assertVisible("@{$band}-prev")
->assertPresent("@{$band}-fade-prev");
$page->script("(() => { const strip = document.querySelector('[data-testid=\"{$band}\"]'); strip.scrollLeft = strip.scrollWidth; })()");
- waitForPostDetailsDialogCondition($page, "!document.querySelector('[data-testid=\"{$band}-next\"]')");
+ waitForGone($page, "@{$band}-next");
$page->assertNotPresent("@{$band}-next")
->assertNotPresent("@{$band}-fade-next");
$page->hover("@{$band}");
- waitForPostDetailsDialogTestId($page, "{$band}-refreshed");
+ waitFor($page, "@{$band}-refreshed");
$page->assertVisible("@{$band}-refreshed")
->assertSeeIn("@{$band}-refreshed", __('posts.publish.metrics.refreshed', ['time' => '2 hours ago']));
@@ -231,7 +214,7 @@ test('the details metrics band scrolls with arrows, shows when it refreshed and
->toBe($insightsPath);
$page->click("@post-details-insights-{$post->id}");
- waitForPostDetailsDialogCondition($page, "location.pathname === '{$insightsPath}'");
+ waitForPath($page, $insightsPath);
$page->assertPathIs($insightsPath)
->assertNoJavaScriptErrors();
@@ -249,7 +232,7 @@ test('the details metrics follow the order of the post content type and network'
$this->actingAs($user);
$page = visit(route('app.posts.index', ['post' => $post->id]));
- waitForPostDetailsDialogTestId($page, "post-details-metrics-{$post->id}");
+ waitFor($page, "@post-details-metrics-{$post->id}");
expect($page->script("[...document.querySelectorAll('[data-testid=\"post-details-metrics-{$post->id}\"] [data-metric]')].map((item) => item.dataset.metric)"))
->toBe($expected);
@@ -291,8 +274,8 @@ test('the metrics band arrows follow the real overflow when the metrics change w
$page = visit($surface === 'dialog'
? route('app.posts.index', ['post' => $post->id])
: route('app.posts.index', ['tab' => 'sent']))->resize($width, 1000);
- waitForPostDetailsDialogTestId($page, $band);
- waitForPostDetailsDialogCondition($page, "document.fonts.status === 'loaded' && document.getAnimations().every((animation) => animation.playState !== 'running')");
+ waitFor($page, "@{$band}");
+ waitForCondition($page, "document.fonts.status === 'loaded' && document.getAnimations().every((animation) => animation.playState !== 'running')");
expect(postDetailsDialogMetricsBandState($page, $band))->toBe(['overflows' => true, 'next' => true, 'fadeNext' => true]);
@@ -304,12 +287,12 @@ test('the metrics band arrows follow the real overflow when the metrics change w
document.head.append(style);
})()
JS);
- waitForPostDetailsDialogCondition($page, "!document.querySelector('[data-testid=\"{$band}-next\"]')");
+ waitForGone($page, "@{$band}-next");
expect(postDetailsDialogMetricsBandState($page, $band))->toBe(['overflows' => false, 'next' => false, 'fadeNext' => false]);
$page->script("document.getElementById('narrow-metrics').remove()");
- waitForPostDetailsDialogTestId($page, "{$band}-next");
+ waitFor($page, "@{$band}-next");
expect(postDetailsDialogMetricsBandState($page, $band))->toBe(['overflows' => true, 'next' => true, 'fadeNext' => true]);
$page->assertNoJavaScriptErrors();
@@ -325,7 +308,7 @@ test('a publishing post shows a spinning status in its details', function () {
$this->actingAs($user);
$page = visit(route('app.posts.index', ['post' => $post->id]));
- waitForPostDetailsDialogTestId($page, "post-details-status-{$post->id}");
+ waitFor($page, "@post-details-status-{$post->id}");
expect($page->script("document.querySelector('[data-testid=\"post-details-status-{$post->id}\"] svg').classList.contains('animate-spin')"))->toBeTrue();
$page->assertNoJavaScriptErrors();
@@ -353,7 +336,7 @@ test('the details of a sent thread show every post of the thread with its own me
$this->actingAs($user);
$page = visit(route('app.posts.index', ['post' => $post->id]));
- waitForPostDetailsDialogTestId($page, "thread-view-{$post->id}");
+ waitFor($page, "@thread-view-{$post->id}");
$page->assertSeeIn("@thread-view-post-{$post->id}-0", 'First post of the thread')
->assertSeeIn("@thread-view-post-{$post->id}-1", 'Second post of the thread')
diff --git a/tests/Browser/PostDetailsGroupTest.php b/tests/Browser/PostDetailsGroupTest.php
index 47f87c3e7..a7f5b3007 100644
--- a/tests/Browser/PostDetailsGroupTest.php
+++ b/tests/Browser/PostDetailsGroupTest.php
@@ -12,18 +12,6 @@ use App\Models\Workspace;
use Carbon\CarbonImmutable;
use Illuminate\Support\Collection;
-function waitForDetailsGroupTestId(mixed $page, string $testId): void
-{
- $page->script(<<<JS
- (async () => {
- for (let attempt = 0; attempt < 100; attempt++) {
- if (document.querySelector('[data-testid="{$testId}"]')?.getBoundingClientRect().height > 0) return;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })();
- JS);
-}
-
/**
* @return array{0: User, 1: Collection<int, Post>}
*/
@@ -58,11 +46,11 @@ function detailsGroupSetup(int $channels): array
function openDetailsFromCard(mixed $page, string $key): void
{
- waitForDetailsGroupTestId($page, "post-card-menu-{$key}");
+ waitFor($page, "@post-card-menu-{$key}");
$page->click("@post-card-menu-{$key}");
- waitForDetailsGroupTestId($page, "post-details-open-{$key}");
+ waitFor($page, "@post-details-open-{$key}");
$page->click("@post-details-open-{$key}");
- waitForDetailsGroupTestId($page, "post-details-{$key}");
+ waitFor($page, "@post-details-{$key}");
}
test('post details lists the posts created together and switches between them', function () {
@@ -74,7 +62,7 @@ test('post details lists the posts created together and switches between them',
$page = visit(route('app.posts.index'));
openDetailsFromCard($page, $first->id);
- waitForDetailsGroupTestId($page, "post-details-rail-{$first->id}");
+ waitFor($page, "@post-details-rail-{$first->id}");
$page->assertSeeIn("@post-details-rail-{$first->id}", __('posts.group.channels', ['count' => 3]));
@@ -88,7 +76,7 @@ test('post details lists the posts created together and switches between them',
->and($page->script("document.querySelector('[data-testid=\"post-details-rail-item-{$first->id}\"]').getAttribute('aria-current')"))->toBe('true');
$page->click("@post-details-rail-item-{$second->id}");
- waitForDetailsGroupTestId($page, "post-details-target-{$second->id}");
+ waitFor($page, "@post-details-target-{$second->id}");
$page->assertSeeIn("@post-details-text-{$second->id}", 'Grouped details post')
->assertSeeIn("@post-details-status-{$first->id}", __('posts.status.scheduled'));
@@ -96,7 +84,7 @@ test('post details lists the posts created together and switches between them',
->and($page->script("document.querySelector('[data-testid=\"post-details-time-{$first->id}\"]').textContent"))->toContain('10:00');
$page->click("@post-details-rail-item-{$draft->id}");
- waitForDetailsGroupTestId($page, "post-details-edit-{$draft->id}");
+ waitFor($page, "@post-details-edit-{$draft->id}");
$page->assertSeeIn("@post-details-status-{$first->id}", __('posts.status.draft'))
->assertMissing("@post-details-publish-now-{$draft->id}");
@@ -127,9 +115,9 @@ test('the channels rail stays in place while only the post details scroll', func
$page = visit(route('app.posts.index'));
$page->resize(1440, 900);
openDetailsFromCard($page, $first->id);
- waitForDetailsGroupTestId($page, "post-details-rail-{$first->id}");
+ waitFor($page, "@post-details-rail-{$first->id}");
- waitForDetailsGroupTestId($page, "post-details-see-more-{$first->id}");
+ waitFor($page, "@post-details-see-more-{$first->id}");
$page->click("@post-details-see-more-{$first->id}");
$railTop = $page->script("document.querySelector('[data-testid=\"post-details-rail-{$first->id}\"]').getBoundingClientRect().top");
$page->script("document.querySelector('[data-testid=\"post-details-body-{$first->id}\"]').scrollTop = 100000");
diff --git a/tests/Browser/PostNotesTest.php b/tests/Browser/PostNotesTest.php
index c4fb12159..8db381df3 100644
--- a/tests/Browser/PostNotesTest.php
+++ b/tests/Browser/PostNotesTest.php
@@ -10,24 +10,6 @@ use App\Models\User;
use App\Models\Workspace;
use Illuminate\Support\Facades\Mail;
-/**
- * Poll browser-side until the testid element has laid out (width/height > 0).
- * These Pest browser assertions do not auto-wait, so settle async UI first.
- */
-function waitForPostNotesTestId(mixed $page, string $testId): void
-{
- $page->script(<<<JS
- (async () => {
- const sel = '[data-testid="{$testId}"]';
- for (let i = 0; i < 100; i++) {
- const el = document.querySelector(sel);
- if (el && el.getBoundingClientRect().height > 0) return;
- await new Promise((r) => setTimeout(r, 50));
- }
- })();
- JS);
-}
-
test('adding a note from the popover shows it and emails the other members', function () {
Mail::fake();
@@ -49,15 +31,15 @@ test('adding a note from the popover shows it and emails the other members', fun
$page = visit(route('app.posts.index', ['tab' => 'drafts']));
- waitForPostNotesTestId($page, "post-notes-trigger-{$post->id}");
+ waitFor($page, "@post-notes-trigger-{$post->id}");
$page->click("@post-notes-trigger-{$post->id}");
- waitForPostNotesTestId($page, 'note-input');
+ waitFor($page, '@note-input');
$page->assertScript('(() => { const field = document.querySelector("[data-testid=note-composer]").getBoundingClientRect(); const send = document.querySelector("[data-testid=note-send]").getBoundingClientRect(); return Math.abs((field.top + field.height / 2) - (send.top + send.height / 2)) <= 1 && send.right <= field.right; })()', true);
$page->fill('@note-input', 'Please check the @image before Friday');
$page->click('@note-send');
- waitForPostNotesTestId($page, 'note-body');
+ waitFor($page, '@note-body');
$page->assertScript('(() => { const list = document.querySelector("[data-testid=notes-list]"); return list.scrollWidth <= list.clientWidth; })()', true);
@@ -92,9 +74,9 @@ test('the note composer enables send only with text and sends on Enter but not S
$page = visit(route('app.posts.index', ['tab' => 'drafts']));
- waitForPostNotesTestId($page, "post-notes-trigger-{$post->id}");
+ waitFor($page, "@post-notes-trigger-{$post->id}");
$page->click("@post-notes-trigger-{$post->id}");
- waitForPostNotesTestId($page, 'notes-empty');
+ waitFor($page, '@notes-empty');
$page->assertVisible('@notes-empty')
->assertMissing("@post-notes-count-{$post->id}")
@@ -112,7 +94,7 @@ test('the note composer enables send only with text and sends on Enter but not S
expect(PostNote::query()->where('post_id', $post->id)->exists())->toBeFalse();
$page->keys('@note-input', ['Enter']);
- waitForPostNotesTestId($page, 'note-body');
+ waitFor($page, '@note-body');
$page->assertSeeIn('@note-body', 'First line')
->assertValue('@note-input', '')
@@ -140,9 +122,9 @@ test('a note timestamp follows the display zone of the list', function () {
$this->actingAs($user);
$page = visit(route('app.posts.index', ['tab' => 'drafts', 'tz' => 'America/Sao_Paulo']));
- waitForPostNotesTestId($page, "post-notes-trigger-{$post->id}");
+ waitFor($page, "@post-notes-trigger-{$post->id}");
$page->click("@post-notes-trigger-{$post->id}");
- waitForPostNotesTestId($page, 'note-created-at');
+ waitFor($page, '@note-created-at');
expect($page->script('document.querySelector(\'[data-testid="note-created-at"]\').getAttribute("title")'))
->toBe($createdAt->setTimezone('America/Sao_Paulo')->format('F j, Y g:i A'));
@@ -164,9 +146,9 @@ test('a note created an hour ago reads as past for a user whose zone is not the
$this->actingAs($user);
$page = visit(route('app.posts.index', ['tab' => 'drafts']));
- waitForPostNotesTestId($page, "post-notes-trigger-{$post->id}");
+ waitFor($page, "@post-notes-trigger-{$post->id}");
$page->click("@post-notes-trigger-{$post->id}");
- waitForPostNotesTestId($page, 'note-created-at');
+ waitFor($page, '@note-created-at');
expect(trim((string) $page->script('document.querySelector(\'[data-testid="note-created-at"]\').textContent')))
->toBe('an hour ago');
@@ -182,16 +164,16 @@ test('the notes toggle says whether it shows or hides the notes', function () {
$this->actingAs($user);
$page = visit(route('app.posts.index', ['tab' => 'drafts']));
- waitForPostNotesTestId($page, "post-notes-trigger-{$post->id}");
+ waitFor($page, "@post-notes-trigger-{$post->id}");
$page->hover("@post-notes-trigger-{$post->id}");
- waitForPostNotesTestId($page, "post-notes-tooltip-{$post->id}");
+ waitFor($page, "@post-notes-tooltip-{$post->id}");
$page->assertSeeIn("@post-notes-tooltip-{$post->id}", __('notes.show'));
$page->click("@post-notes-trigger-{$post->id}");
- waitForPostNotesTestId($page, 'note-input');
+ waitFor($page, '@note-input');
$page->hover('@note-input')->hover("@post-notes-trigger-{$post->id}");
- waitForPostNotesTestId($page, "post-notes-tooltip-{$post->id}");
+ waitFor($page, "@post-notes-tooltip-{$post->id}");
$page->assertSeeIn("@post-notes-tooltip-{$post->id}", __('notes.hide'))
->assertNoJavaScriptErrors();
@@ -207,33 +189,19 @@ test('the notes count follows the thread when it opens and when a note is delete
$this->actingAs($user);
$page = visit(route('app.posts.index', ['tab' => 'drafts']));
- waitForPostNotesTestId($page, "post-notes-count-{$post->id}");
+ waitFor($page, "@post-notes-count-{$post->id}");
$page->assertSeeIn("@post-notes-count-{$post->id}", '1');
PostNote::factory()->create(['post_id' => $post->id, 'user_id' => $user->id, 'body' => 'Second']);
$page->click("@post-notes-trigger-{$post->id}");
- waitForPostNotesTestId($page, 'note-body');
- $page->script(<<<'JS'
- (async () => {
- for (let i = 0; i < 100; i++) {
- if (document.querySelectorAll('[data-testid="note-item"]').length === 2) return;
- await new Promise((r) => setTimeout(r, 50));
- }
- })();
- JS);
+ waitFor($page, '@note-body');
+ waitForCount($page, '@note-item', 2);
$page->assertSeeIn("@post-notes-count-{$post->id}", '2');
$page->hover('@note-item')->click('@note-actions');
- waitForPostNotesTestId($page, 'note-delete');
+ waitFor($page, '@note-delete');
$page->click('@note-delete');
- $page->script(<<<'JS'
- (async () => {
- for (let i = 0; i < 100; i++) {
- if (document.querySelectorAll('[data-testid="note-item"]').length === 1) return;
- await new Promise((r) => setTimeout(r, 50));
- }
- })();
- JS);
+ waitForCount($page, '@note-item', 1);
$page->assertSeeIn("@post-notes-count-{$post->id}", '1')->assertNoJavaScriptErrors();
});
@@ -251,9 +219,9 @@ test('notes open, grow, send, edit and fit the card on every tab, on desktop and
$this->actingAs($user);
$page = visit(route('app.posts.index', ['tab' => $tab]))->resize($width, 900);
- waitForPostNotesTestId($page, "post-notes-trigger-{$post->id}");
+ waitFor($page, "@post-notes-trigger-{$post->id}");
$page->click("@post-notes-trigger-{$post->id}");
- waitForPostNotesTestId($page, 'note-input');
+ waitFor($page, '@note-input');
$singleLine = $page->script("document.querySelector('[data-testid=\"note-input\"]').getBoundingClientRect().height");
$page->fill('@note-input', "First line\nSecond line\nThird line");
@@ -261,24 +229,18 @@ test('notes open, grow, send, edit and fit the card on every tab, on desktop and
expect($grown)->toBeGreaterThan($singleLine);
$page->keys('@note-input', ['Enter']);
- waitForPostNotesTestId($page, 'note-body');
+ waitFor($page, '@note-body');
$page->assertSeeIn("@post-notes-count-{$post->id}", '1')
->assertScript('document.documentElement.scrollWidth <= window.innerWidth', true);
$page->hover('@note-item')->click('@note-actions');
- waitForPostNotesTestId($page, 'note-edit');
+ waitFor($page, '@note-edit');
$page->click('@note-edit');
- waitForPostNotesTestId($page, 'note-edit-input');
+ waitFor($page, '@note-edit-input');
$page->fill('@note-edit-input', 'Edited note')
->click('@note-edit-save');
- $page->script(<<<'JS'
- (async () => {
- for (let i = 0; i < 100; i++) {
- if (!document.querySelector('[data-testid="note-edit-input"]') && document.querySelector('[data-testid="note-body"]')?.textContent.includes('Edited note')) return;
- await new Promise((r) => setTimeout(r, 50));
- }
- })();
- JS);
+ waitForGone($page, '@note-edit-input');
+ waitForText($page, '@note-body', 'Edited note');
$page->assertSeeIn('@note-body', 'Edited note')
->assertScript('document.documentElement.scrollWidth <= window.innerWidth', true)
diff --git a/tests/Browser/PostRecurrenceTest.php b/tests/Browser/PostRecurrenceTest.php
index 903635f51..08db26299 100644
--- a/tests/Browser/PostRecurrenceTest.php
+++ b/tests/Browser/PostRecurrenceTest.php
@@ -11,30 +11,6 @@ use App\Models\User;
use App\Models\Workspace;
use Carbon\CarbonImmutable;
-function waitForRecurrenceTestId(mixed $page, string $testId): void
-{
- $page->script(<<<JS
- (async () => {
- for (let attempt = 0; attempt < 100; attempt++) {
- if (document.querySelector('[data-testid="{$testId}"]')?.getBoundingClientRect().height > 0) return;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })();
- JS);
-}
-
-function waitForRecurrenceCondition(mixed $page, string $condition): void
-{
- $page->script(<<<JS
- (async () => {
- for (let attempt = 0; attempt < 100; attempt++) {
- if ({$condition}) return;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })();
- JS);
-}
-
function recurrenceText(mixed $page, string $testId): string
{
return $page->script("document.querySelector('[data-testid=\"{$testId}\"]')?.textContent.replace(/\\s+/g, ' ').trim() ?? ''");
@@ -73,19 +49,20 @@ function recurrenceSetup(string $channelZone = 'UTC', ?CarbonImmutable $at = nul
function openRecurrenceDialog(mixed $page, string $key): void
{
- waitForRecurrenceTestId($page, "post-card-menu-{$key}");
+ waitFor($page, "@post-card-menu-{$key}");
$page->click("@post-card-menu-{$key}");
- waitForRecurrenceTestId($page, "post-recurrence-open-{$key}");
+ waitFor($page, "@post-recurrence-open-{$key}");
$page->click("@post-recurrence-open-{$key}");
- waitForRecurrenceTestId($page, "post-recurrence-dialog-{$key}");
+ waitFor($page, "@post-recurrence-dialog-{$key}");
}
function chooseRecurrenceFrequency(mixed $page, string $postId, string $frequency): void
{
$page->click("@post-recurrence-frequency-{$postId}");
- waitForRecurrenceTestId($page, "post-recurrence-frequency-option-{$frequency}");
+ waitFor($page, "@post-recurrence-frequency-option-{$frequency}");
$page->click("@post-recurrence-frequency-option-{$frequency}");
- waitForRecurrenceCondition($page, "document.querySelector('[data-testid=\"post-recurrence-frequency-{$postId}\"]')?.dataset.value === '{$frequency}' && !document.querySelector('[data-testid=\"post-recurrence-frequency-option-{$frequency}\"]')");
+ waitForState($page, "@post-recurrence-frequency-{$postId}", "element.dataset.value === '{$frequency}'");
+ waitForGone($page, "@post-recurrence-frequency-option-{$frequency}");
}
test('a scheduled post is made recurring from its card menu', function () {
@@ -93,7 +70,7 @@ test('a scheduled post is made recurring from its card menu', function () {
$this->actingAs($user);
$page = visit(route('app.posts.index'));
- waitForRecurrenceTestId($page, "post-card-{$post->id}");
+ waitFor($page, "@post-card-{$post->id}");
$page->assertMissing("@post-recurrence-banner-{$post->id}")
->assertMissing("@post-recurring-{$post->id}");
@@ -108,13 +85,13 @@ test('a scheduled post is made recurring from its card menu', function () {
chooseRecurrenceFrequency($page, $post->id, 'month');
$page->fill("@post-recurrence-times-{$post->id}", '3');
$monthly = "This post will be shared every month on the {$scheduledAt->format('jS')} at {$time}, until {$scheduledAt->addMonthsNoOverflow(3)->format('M j, Y')}.";
- waitForRecurrenceCondition($page, "document.querySelector('[data-testid=\"post-recurrence-summary-{$post->id}\"]')?.textContent.includes('month')");
+ waitForText($page, "@post-recurrence-summary-{$post->id}", 'month');
expect(recurrenceText($page, "post-recurrence-summary-{$post->id}"))->toBe($monthly);
$page->fill("@post-recurrence-interval-{$post->id}", '2');
chooseRecurrenceFrequency($page, $post->id, 'day');
- waitForRecurrenceCondition($page, "document.querySelector('[data-testid=\"post-recurrence-summary-{$post->id}\"]')?.textContent.includes('days')");
+ waitForText($page, "@post-recurrence-summary-{$post->id}", 'days');
expect(recurrenceText($page, "post-recurrence-summary-{$post->id}"))
->toBe("This post will be shared every 2 days at {$time}, until {$scheduledAt->addDays(6)->format('M j, Y')}.");
@@ -122,7 +99,7 @@ test('a scheduled post is made recurring from its card menu', function () {
chooseRecurrenceFrequency($page, $post->id, 'week');
$page->fill("@post-recurrence-interval-{$post->id}", '1');
$page->click("@post-recurrence-save-{$post->id}");
- waitForRecurrenceTestId($page, "post-recurrence-banner-{$post->id}");
+ waitFor($page, "@post-recurrence-banner-{$post->id}");
expect($post->refresh()->recurrence_frequency)->toBe(RecurrenceFrequency::Week)
->and($post->recurrence_interval)->toBe(1)
@@ -142,14 +119,14 @@ test('a recurrence is edited and stopped', function () {
$this->actingAs($user);
$page = visit(route('app.posts.index'));
- waitForRecurrenceTestId($page, "post-recurrence-banner-{$post->id}");
+ waitFor($page, "@post-recurrence-banner-{$post->id}");
$page->assertSeeIn("@post-recurrence-banner-{$post->id}", '(2 posts left)');
$page->click("@post-card-menu-{$post->id}");
- waitForRecurrenceTestId($page, "post-recurrence-open-{$post->id}");
+ waitFor($page, "@post-recurrence-open-{$post->id}");
$page->assertSeeIn("@post-recurrence-open-{$post->id}", __('posts.recurrence.edit'));
$page->click("@post-recurrence-open-{$post->id}");
- waitForRecurrenceTestId($page, "post-recurrence-dialog-{$post->id}");
+ waitFor($page, "@post-recurrence-dialog-{$post->id}");
expect($page->script("document.querySelector('[data-testid=\"post-recurrence-frequency-{$post->id}\"]').dataset.value"))->toBe('day')
->and($page->script("document.querySelector('[data-testid=\"post-recurrence-times-{$post->id}\"]').value"))->toBe('2');
@@ -162,13 +139,13 @@ test('a recurrence is edited and stopped', function () {
$page->fill("@post-recurrence-times-{$post->id}", '5');
$page->click("@post-recurrence-save-{$post->id}");
- waitForRecurrenceCondition($page, "document.querySelector('[data-testid=\"post-recurrence-banner-{$post->id}\"]')?.textContent.includes('5 posts left')");
+ waitForText($page, "@post-recurrence-banner-{$post->id}", '5 posts left');
expect($post->refresh()->recurrence_remaining)->toBe(5);
openRecurrenceDialog($page, $post->id);
$page->click("@post-recurrence-stop-{$post->id}");
- waitForRecurrenceCondition($page, "!document.querySelector('[data-testid=\"post-recurrence-banner-{$post->id}\"]')");
+ waitForGone($page, "@post-recurrence-banner-{$post->id}");
expect($post->refresh()->isRecurring())->toBeFalse();
$page->assertMissing("@post-recurrence-banner-{$post->id}")
@@ -189,7 +166,7 @@ test('the banner of a later occurrence counts from the series origin', function
$this->actingAs($user);
$page = visit(route('app.posts.index'));
- waitForRecurrenceTestId($page, "post-recurrence-banner-{$post->id}");
+ waitFor($page, "@post-recurrence-banner-{$post->id}");
expect(recurrenceText($page, "post-recurrence-banner-{$post->id}"))
->toBe("This post will be shared every month on the 31st at 9:00 AM, until Apr 30, {$year} (2 posts left).");
@@ -203,7 +180,7 @@ test('the end date of a recurrence follows the channel time zone', function () {
$this->actingAs($user);
$page = visit(route('app.posts.index'));
- waitForRecurrenceTestId($page, "post-card-{$post->id}");
+ waitFor($page, "@post-card-{$post->id}");
openRecurrenceDialog($page, $post->id);
expect(recurrenceText($page, "post-recurrence-summary-{$post->id}"))
@@ -211,7 +188,7 @@ test('the end date of a recurrence follows the channel time zone', function () {
chooseRecurrenceFrequency($page, $post->id, 'month');
$page->fill("@post-recurrence-times-{$post->id}", '6');
- waitForRecurrenceCondition($page, "document.querySelector('[data-testid=\"post-recurrence-summary-{$post->id}\"]')?.textContent.includes('month')");
+ waitForText($page, "@post-recurrence-summary-{$post->id}", 'month');
expect(recurrenceText($page, "post-recurrence-summary-{$post->id}"))
->toBe("This post will be shared every month on the 31st at 10:00 PM, until {$localDay->addMonthsNoOverflow(6)->format('M j, Y')}.");
diff --git a/tests/Browser/PreferencesPageTest.php b/tests/Browser/PreferencesPageTest.php
index 9871b8aa4..cfcd94952 100644
--- a/tests/Browser/PreferencesPageTest.php
+++ b/tests/Browser/PreferencesPageTest.php
@@ -9,20 +9,6 @@ use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
-function waitForPreferencesTestId(mixed $page, string $testId): void
-{
- $page->script(<<<JS
- (async () => {
- const sel = '[data-testid="{$testId}"]';
- for (let i = 0; i < 150; i++) {
- const el = document.querySelector(sel);
- if (el && el.getBoundingClientRect().height > 0) return;
- await new Promise((r) => setTimeout(r, 50));
- }
- })();
- JS);
-}
-
function preferencesUser(array $attributes = []): User
{
$user = User::factory()->create($attributes);
@@ -38,20 +24,20 @@ function preferencesUser(array $attributes = []): User
function choosePreference(mixed $page, string $testid, string $value, string $savedField): void
{
- waitForPreferencesTestId($page, "{$testid}-trigger");
+ waitFor($page, "@{$testid}-trigger");
$page->click("@{$testid}-trigger");
- waitForPreferencesTestId($page, "{$testid}-option-{$value}");
+ waitFor($page, "@{$testid}-option-{$value}");
$page->click("@{$testid}-option-{$value}");
- waitForPreferencesTestId($page, "preferences-saved-{$savedField}");
+ waitFor($page, "@preferences-saved-{$savedField}");
}
test('the preferences page lists every preference and is linked from the settings sidebar', function () {
$this->actingAs(preferencesUser());
$page = visit(route('app.profile.edit'));
- waitForPreferencesTestId($page, 'settings-nav-preferences');
+ waitFor($page, '@settings-nav-preferences');
$page->click('@settings-nav-preferences');
- waitForPreferencesTestId($page, 'preferences-page');
+ waitFor($page, '@preferences-page');
$page->assertVisible('@preferences-theme-trigger')
->assertVisible('@preferences-language-trigger')
@@ -73,7 +59,7 @@ test('choosing dark applies it at once and the server renders it on the next loa
expect($user->fresh()->theme)->toBe(Theme::Dark);
$page = visit(route('app.settings.preferences'))->inLightMode();
- waitForPreferencesTestId($page, 'preferences-page');
+ waitFor($page, '@preferences-page');
$page->assertScript("document.documentElement.classList.contains('dark')", true)
->assertNoJavaScriptErrors();
});
@@ -82,11 +68,11 @@ test('the system theme follows the operating system', function () {
$this->actingAs(preferencesUser(['theme' => Theme::System]));
$dark = visit(route('app.settings.preferences'))->inDarkMode();
- waitForPreferencesTestId($dark, 'preferences-page');
+ waitFor($dark, '@preferences-page');
$dark->assertScript("document.documentElement.classList.contains('dark')", true);
$light = visit(route('app.settings.preferences'))->inLightMode();
- waitForPreferencesTestId($light, 'preferences-page');
+ waitFor($light, '@preferences-page');
$light->assertScript("document.documentElement.classList.contains('dark')", false)
->assertNoJavaScriptErrors();
});
@@ -97,10 +83,10 @@ test('the language picker suggests the browser language, filters as you type and
$toastAppears = "(async () => { for (let i = 0; i < 20; i++) { if (document.querySelector('[data-sonner-toast]')) return true; await new Promise((r) => setTimeout(r, 50)); } return false; })();";
$page = visit(route('app.settings.preferences'))->withLocale('pt-PT');
- waitForPreferencesTestId($page, 'preferences-language-trigger');
+ waitFor($page, '@preferences-language-trigger');
$page->click('@preferences-language-trigger');
- waitForPreferencesTestId($page, 'preferences-language-suggestions');
+ waitFor($page, '@preferences-language-suggestions');
$page->assertVisible('[data-testid="preferences-language-suggestions"] [data-testid="preferences-language-option-pt-BR"]')
->assertVisible('@preferences-language-detected')
@@ -113,19 +99,19 @@ test('the language picker suggests the browser language, filters as you type and
->assertVisible('@preferences-language-option-de');
$page->fill('@preferences-language-search', 'francais');
- waitForPreferencesTestId($page, 'preferences-language-option-fr');
+ waitFor($page, '@preferences-language-option-fr');
$page->assertVisible('@preferences-language-option-fr')
->assertMissing('@preferences-language-option-de');
$page->fill('@preferences-language-search', 'Portug');
- waitForPreferencesTestId($page, 'preferences-language-option-pt-BR');
+ waitFor($page, '@preferences-language-option-pt-BR');
$page->assertVisible('@preferences-language-option-pt-BR')
->assertMissing('@preferences-language-option-de')
->click('@preferences-language-option-pt-BR');
- waitForPreferencesTestId($page, 'preferences-saved-locale');
+ waitFor($page, '@preferences-saved-locale');
$title = __('settings.preferences.title', [], 'pt-BR');
- $page->script("(async () => { for (let i = 0; i < 150; i++) { if (document.body.innerText.includes('{$title}')) return; await new Promise((r) => setTimeout(r, 50)); } })();");
+ waitForState($page, 'body', "element.innerText.includes('{$title}')");
expect($page->script($toastAppears))->toBeFalse();
$page->assertSeeIn('@header-title', $title)->assertNoJavaScriptErrors();
@@ -148,9 +134,9 @@ test('a zone that is the user, browser and channel zone is suggested once with e
$this->actingAs($user);
$page = visit(route('app.settings.preferences'))->withTimezone('Europe/Warsaw');
- waitForPreferencesTestId($page, 'preferences-timezone-trigger');
+ waitFor($page, '@preferences-timezone-trigger');
$page->click('@preferences-timezone-trigger');
- waitForPreferencesTestId($page, 'preferences-timezone-suggestion-reasons-Europe-Warsaw');
+ waitFor($page, '@preferences-timezone-suggestion-reasons-Europe-Warsaw');
$reasons = 'document.querySelector(\'[data-testid="preferences-timezone-suggestion-reasons-Europe-Warsaw"]\')';
@@ -181,7 +167,7 @@ test('a zone that is the user, browser and channel zone is suggested once with e
JS, true);
$page->hover('@preferences-timezone-option-Europe-Warsaw');
- waitForPreferencesTestId($page, 'preferences-timezone-suggestion-tooltip');
+ waitFor($page, '@preferences-timezone-suggestion-tooltip');
$page->assertScript('document.querySelector(\'[data-testid="preferences-timezone-suggestion-tooltip"]\').getBoundingClientRect().right <= document.querySelector(\'[data-testid="preferences-timezone-search"]\').closest(\'[data-slot="popover-content"]\').getBoundingClientRect().left', true);
@@ -197,20 +183,20 @@ test('without channels the picker shows no empty group, search filters both grou
$this->actingAs($user);
$page = visit(route('app.settings.preferences'))->withTimezone('UTC');
- waitForPreferencesTestId($page, 'preferences-timezone-trigger');
+ waitFor($page, '@preferences-timezone-trigger');
$page->click('@preferences-timezone-trigger');
- waitForPreferencesTestId($page, 'preferences-timezone-suggestions');
+ waitFor($page, '@preferences-timezone-suggestions');
$page->assertScript('document.querySelectorAll(\'[data-testid="preferences-timezone-suggestions"] [data-testid^="preferences-timezone-option-"]\').length', 1)
->assertScript('document.querySelectorAll(\'[data-testid^="preferences-timezone-suggestion-channel-"]\').length', 0);
$page->type('@preferences-timezone-search', 'Auckland');
- waitForPreferencesTestId($page, 'preferences-timezone-option-Pacific-Auckland');
+ waitFor($page, '@preferences-timezone-option-Pacific-Auckland');
$page->assertMissing('@preferences-timezone-suggestions')
->assertMissing('@preferences-timezone-option-UTC')
->click('@preferences-timezone-option-Pacific-Auckland');
- waitForPreferencesTestId($page, 'preferences-saved-timezone');
+ waitFor($page, '@preferences-saved-timezone');
$page->assertNoJavaScriptErrors();
expect($user->fresh()->timezone)->toBe('Pacific/Auckland');
@@ -222,26 +208,26 @@ test('the time format offers two clocks, keeps its value after a language change
$toastAppears = "(async () => { for (let i = 0; i < 20; i++) { if (document.querySelector('[data-sonner-toast]')) return true; await new Promise((r) => setTimeout(r, 50)); } return false; })();";
$page = visit(route('app.settings.preferences'));
- waitForPreferencesTestId($page, 'preferences-time-format-trigger');
+ waitFor($page, '@preferences-time-format-trigger');
$page->click('@preferences-time-format-trigger');
- waitForPreferencesTestId($page, 'preferences-time-format-option-12h');
+ waitFor($page, '@preferences-time-format-option-12h');
expect($page->script('document.querySelectorAll(\'[data-testid^="preferences-time-format-option-"]\').length'))->toBe(2);
$page->click('@preferences-time-format-option-12h');
- waitForPreferencesTestId($page, 'preferences-saved-time_format');
+ waitFor($page, '@preferences-saved-time_format');
expect($page->script($toastAppears))->toBeFalse()
->and($user->fresh()->time_format)->toBe(TimeFormat::TwelveHour);
choosePreference($page, 'preferences-language', 'de', 'locale');
$label = __('settings.preferences.time_format.twelve_hour', [], 'de');
- $page->script("(async () => { for (let i = 0; i < 150; i++) { if (document.querySelector('[data-testid=\"preferences-time-format-value\"]')?.textContent.includes('{$label}')) return; await new Promise((r) => setTimeout(r, 50)); } })();");
+ waitForState($page, '@preferences-time-format-value', "element.textContent.includes('{$label}')");
$page->assertSeeIn('@preferences-time-format-value', $label)->assertNoJavaScriptErrors();
expect($user->fresh()->time_format)->toBe(TimeFormat::TwelveHour);
$page = visit(route('app.calendar', ['view' => 'week']));
- waitForPreferencesTestId($page, 'calendar-slot-'.now()->startOfWeek()->format('Y-m-d').'-14');
+ waitFor($page, '@calendar-slot-'.now()->startOfWeek()->format('Y-m-d').'-14');
$page->assertScript("document.body.innerText.includes('2 PM')", true)
->assertNoJavaScriptErrors();
@@ -252,18 +238,12 @@ test('the time zone search ignores accents and matches each word typed', functio
$this->actingAs($user);
$page = visit(route('app.settings.preferences'))->withTimezone('UTC');
- waitForPreferencesTestId($page, 'preferences-timezone-trigger');
+ waitFor($page, '@preferences-timezone-trigger');
$page->click('@preferences-timezone-trigger');
- waitForPreferencesTestId($page, 'preferences-timezone-search');
+ waitFor($page, '@preferences-timezone-search');
$page->type('@preferences-timezone-search', 'sao paulo');
- $page->script(<<<'JS'
- (async () => {
- for (let i = 0; i < 100 && !document.querySelector('[data-testid^="preferences-timezone-option-America-Sao"]'); i++) {
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })()
- JS);
+ waitForState($page, '[data-testid^="preferences-timezone-option-America-Sao"]', 'true');
$page->assertScript('Boolean(document.querySelector(\'[data-testid^="preferences-timezone-option-America-Sao"]\'))', true)
->assertMissing('@preferences-timezone-option-UTC')
@@ -275,18 +255,12 @@ test('the time zone search matches the offset shown next to each zone', function
$this->actingAs($user);
$page = visit(route('app.settings.preferences'))->withTimezone('UTC');
- waitForPreferencesTestId($page, 'preferences-timezone-trigger');
+ waitFor($page, '@preferences-timezone-trigger');
$page->click('@preferences-timezone-trigger');
- waitForPreferencesTestId($page, 'preferences-timezone-search');
+ waitFor($page, '@preferences-timezone-search');
$page->type('@preferences-timezone-search', 'gmt-3 paulo');
- $page->script(<<<'JS'
- (async () => {
- for (let i = 0; i < 100 && document.querySelector('[data-testid="preferences-timezone-option-UTC"]'); i++) {
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })()
- JS);
+ waitForGone($page, '@preferences-timezone-option-UTC');
$page->assertScript('Array.from(document.querySelectorAll(\'[data-testid^="preferences-timezone-option-"]\')).map((option) => option.dataset.testid.replace("preferences-timezone-option-", "")).join(",")', 'America-Sao_Paulo')
->assertNoJavaScriptErrors();
diff --git a/tests/Browser/ProfilePasswordRequirementsTest.php b/tests/Browser/ProfilePasswordRequirementsTest.php
index 17d6db3b6..338c8474a 100644
--- a/tests/Browser/ProfilePasswordRequirementsTest.php
+++ b/tests/Browser/ProfilePasswordRequirementsTest.php
@@ -4,26 +4,12 @@ declare(strict_types=1);
use App\Models\User;
-function waitForProfilePasswordRequirement(mixed $page, string $key, string $met): void
-{
- $page->script(<<<JS
- (async () => {
- const selector = '[data-testid="password-requirement-{$key}"][data-met="{$met}"]';
- for (let attempt = 0; attempt < 200; attempt++) {
- const element = document.querySelector(selector);
- if (element && element.getBoundingClientRect().height > 0) return;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })();
- JS);
-}
-
test('setting or changing a password shows the same requirements as sign up', function (bool $hasPassword) {
$user = User::factory()->create($hasPassword ? [] : ['password' => null]);
$this->actingAs($user);
$page = visit(route('app.profile.edit', ['tab' => 'login']));
- waitForProfilePasswordRequirement($page, 'min', 'false');
+ waitFor($page, '@password-requirement-min[data-met="false"]');
$page->assertSeeIn('@password-requirement-min', 'At least 12 characters')
->assertAttribute('@password-requirement-mixed_case', 'data-met', 'false')
@@ -31,7 +17,7 @@ test('setting or changing a password shows the same requirements as sign up', fu
->assertAttribute('@password-requirement-symbol', 'data-met', 'false');
$page->type('@profile-new-password', 'abcD1!abcdef');
- waitForProfilePasswordRequirement($page, 'min', 'true');
+ waitFor($page, '@password-requirement-min[data-met="true"]');
$page->assertAttribute('@password-requirement-min', 'data-met', 'true')
->assertAttribute('@password-requirement-mixed_case', 'data-met', 'true')
diff --git a/tests/Browser/ProfileTabsTest.php b/tests/Browser/ProfileTabsTest.php
index 9fafcc3dd..8966ab38f 100644
--- a/tests/Browser/ProfileTabsTest.php
+++ b/tests/Browser/ProfileTabsTest.php
@@ -6,35 +6,21 @@ use App\Enums\User\Theme;
use App\Models\User;
use Illuminate\Support\Facades\DB;
-function waitForProfileTabsTestId(mixed $page, string $testId): void
-{
- $page->script(<<<JS
- (async () => {
- const selector = '[data-testid="{$testId}"]';
- for (let attempt = 0; attempt < 200; attempt++) {
- const element = document.querySelector(selector);
- if (element && element.getBoundingClientRect().height > 0) return;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })();
- JS);
-}
-
test('the profile tabs keep password, login and sessions apart and remember the open tab in the url', function () {
$this->actingAs(User::factory()->create());
$page = visit(route('app.profile.edit'));
- waitForProfileTabsTestId($page, 'profile-tab-login');
+ waitFor($page, '@profile-tab-login');
$page->assertVisible('[data-test="update-profile-button"]')
->assertMissing('@profile-new-password')
->click('@profile-tab-login');
- waitForProfileTabsTestId($page, 'profile-new-password');
+ waitFor($page, '@profile-new-password');
$page->assertVisible('[data-test="connected-account-google"]')
->assertQueryStringHas('tab', 'login')
->click('@profile-tab-sessions');
- waitForProfileTabsTestId($page, 'profile-sessions');
+ waitFor($page, '@profile-sessions');
$page->assertQueryStringHas('tab', 'sessions')
->assertMissing('@profile-new-password')
@@ -45,7 +31,7 @@ test('a link to the login tab opens it', function () {
$this->actingAs(User::factory()->create());
$page = visit(route('app.profile.edit', ['tab' => 'login']));
- waitForProfileTabsTestId($page, 'profile-new-password');
+ waitFor($page, '@profile-new-password');
$page->assertVisible('@profile-new-password')
->assertMissing('[data-test="update-profile-button"]')
@@ -56,7 +42,7 @@ test('the delete account button sits under a neutral warning', function () {
$this->actingAs(User::factory()->create());
$page = visit(route('app.profile.edit'));
- waitForProfileTabsTestId($page, 'delete-account-warning');
+ waitFor($page, '@delete-account-warning');
expect($page->script(<<<'JS'
(() => {
@@ -84,7 +70,7 @@ test('each session shows its browser and system icons under the log out button',
$this->actingAs($user);
$page = visit(route('app.profile.edit', ['tab' => 'sessions']));
- waitForProfileTabsTestId($page, 'session-browser-icon-firefox-on-windows');
+ waitFor($page, '@session-browser-icon-firefox-on-windows');
$page->assertAttribute('@session-browser-icon-firefox-on-windows', 'src', '/images/browsers/firefox.svg')
->assertAttribute('@session-os-icon-firefox-on-windows', 'src', '/images/os/windows.png')
@@ -114,7 +100,7 @@ test('the apple logo of a mac session turns light on the dark theme', function (
$this->actingAs($user);
$page = visit(route('app.profile.edit', ['tab' => 'sessions']));
- waitForProfileTabsTestId($page, 'session-os-icon-safari-on-mac');
+ waitFor($page, '@session-os-icon-safari-on-mac');
expect($page->script('getComputedStyle(document.querySelector(\'[data-testid="session-os-icon-safari-on-mac"]\')).filter'))->toBe('invert(1)');
$page->assertNoJavaScriptErrors();
@@ -124,7 +110,7 @@ test('the github mark is drawn in the text color on the dark theme while google
$this->actingAs(User::factory()->create(['theme' => Theme::Dark]));
$page = visit(route('app.profile.edit', ['tab' => 'login']));
- waitForProfileTabsTestId($page, 'connected-account-icon-github');
+ waitFor($page, '@connected-account-icon-github');
$github = $page->script(<<<'JS'
(() => {
@@ -151,16 +137,14 @@ test('logging out other devices asks for a plain confirmation without a password
$this->actingAs($user);
$page = visit(route('app.profile.edit', ['tab' => 'sessions']));
- waitForProfileTabsTestId($page, 'session-browser-icon-phone');
+ waitFor($page, '@session-browser-icon-phone');
$page->click('[data-test="log-out-other-sessions-button"]');
- waitForProfileTabsTestId($page, 'confirm-log-out-other-sessions');
+ waitFor($page, '@confirm-log-out-other-sessions');
expect($page->script('document.querySelectorAll(\'[data-testid="confirm-delete-modal"] input\').length'))->toBe(0);
$page->click('@confirm-log-out-other-sessions');
- for ($attempt = 0; $attempt < 50 && DB::table($table)->whereIn('id', ['phone', 'laptop'])->exists(); $attempt++) {
- $page->script('new Promise((resolve) => setTimeout(resolve, 100))');
- }
+ waitForDatabase($page, fn () => ! DB::table($table)->whereIn('id', ['phone', 'laptop'])->exists());
expect(DB::table($table)->whereIn('id', ['phone', 'laptop'])->exists())->toBeFalse();
$page->assertNoJavaScriptErrors();
diff --git a/tests/Browser/PublishCardActionsTest.php b/tests/Browser/PublishCardActionsTest.php
index 4ae072a1c..516a7f42f 100644
--- a/tests/Browser/PublishCardActionsTest.php
+++ b/tests/Browser/PublishCardActionsTest.php
@@ -13,30 +13,6 @@ use App\Models\Workspace;
use App\Support\PostingSchedule;
use Illuminate\Support\Facades\Queue;
-function waitForCardActionsTestId(mixed $page, string $testId): void
-{
- $page->script(<<<JS
- (async () => {
- for (let attempt = 0; attempt < 100; attempt++) {
- if (document.querySelector('[data-testid="{$testId}"]')?.getBoundingClientRect().height > 0) return;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })();
- JS);
-}
-
-function waitForCardActionsCondition(mixed $page, string $condition): void
-{
- $page->script(<<<JS
- (async () => {
- for (let attempt = 0; attempt < 100; attempt++) {
- if ({$condition}) return;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })();
- JS);
-}
-
/**
* @return list<string>
*/
@@ -50,9 +26,9 @@ function cardActionsMenuItems(mixed $page, string $key): array
function openCardActionsMenu(mixed $page, string $key): void
{
- waitForCardActionsTestId($page, "post-card-menu-{$key}");
+ waitFor($page, "@post-card-menu-{$key}");
$page->click("@post-card-menu-{$key}");
- waitForCardActionsTestId($page, "post-card-menu-content-{$key}");
+ waitFor($page, "@post-card-menu-content-{$key}");
}
/**
@@ -111,7 +87,7 @@ test('a queued card shows publish now, edit and the menu in order', function ()
$this->actingAs($user);
$page = visit(route('app.posts.index'));
- waitForCardActionsTestId($page, "post-publish-now-{$queued->id}");
+ waitFor($page, "@post-publish-now-{$queued->id}");
$footer = $page->script(<<<JS
Array.from(document.querySelector('[data-testid="post-publish-now-{$queued->id}"]').parentElement.children)
@@ -169,12 +145,10 @@ test('publish now on a queued card sends the post', function () {
$this->actingAs($user);
$page = visit(route('app.posts.index'));
- waitForCardActionsTestId($page, "post-publish-now-{$queued->id}");
+ waitFor($page, "@post-publish-now-{$queued->id}");
$page->click("@post-publish-now-{$queued->id}");
- for ($attempt = 0; $attempt < 50 && $queued->refresh()->status !== PostStatus::Publishing; $attempt++) {
- $page->script('new Promise((resolve) => setTimeout(resolve, 100))');
- }
+ waitForDatabase($page, fn () => $queued->refresh()->status === PostStatus::Publishing);
expect($queued->refresh()->status)->toBe(PostStatus::Publishing);
$page->assertNoJavaScriptErrors();
@@ -186,12 +160,12 @@ test('move to drafts takes the card out of the queue and updates the tab counts'
$this->actingAs($user);
$page = visit(route('app.posts.index'));
- waitForCardActionsTestId($page, 'publish-tab-count-queue');
+ waitFor($page, '@publish-tab-count-queue');
$page->assertSeeIn('@publish-tab-count-queue', '1');
openCardActionsMenu($page, $queued->id);
$page->click("@post-move-drafts-{$queued->id}");
- waitForCardActionsCondition($page, "!document.querySelector('[data-testid=\"post-card-{$queued->id}\"]')");
+ waitForGone($page, "@post-card-{$queued->id}");
expect($queued->refresh()->status)->toBe(PostStatus::Draft);
$page->assertMissing("@post-card-{$queued->id}")
@@ -209,7 +183,7 @@ test('duplicate creates a copy and opens it in the composer', function () {
$page = visit(route('app.posts.index'));
openCardActionsMenu($page, $queued->id);
$page->click("@post-duplicate-{$queued->id}");
- waitForCardActionsTestId($page, 'post-composer-dialog');
+ waitFor($page, '@post-composer-dialog');
$copy = Post::query()->where('workspace_id', $workspace->id)->whereKeyNot($queued->id)->first();
@@ -228,7 +202,7 @@ test('post details opens a read-only preview of the post', function () {
$page = visit(route('app.posts.index'));
openCardActionsMenu($page, $queued->id);
$page->click("@post-details-open-{$queued->id}");
- waitForCardActionsTestId($page, "post-details-{$queued->id}");
+ waitFor($page, "@post-details-{$queued->id}");
$page->assertSeeIn("@post-details-{$queued->id}", __('posts.show.title'))
->assertSeeIn("@post-details-status-{$queued->id}", __('posts.status.scheduled'))
@@ -303,14 +277,14 @@ test('a sent post with a link offers to share it in a new post and to copy it',
$page->script('window.__copied = null; navigator.clipboard.writeText = async (text) => { window.__copied = text; };');
$page->click("@post-copy-link-{$published->id}");
- waitForCardActionsCondition($page, 'window.__copied !== null');
+ waitForCondition($page, 'window.__copied !== null');
expect($page->script('window.__copied'))->toBe($url);
openCardActionsMenu($page, $published->id);
$page->click("@post-share-link-{$published->id}");
- waitForCardActionsTestId($page, 'post-composer-dialog');
- waitForCardActionsTestId($page, "composer-account-{$channel->id}");
- waitForCardActionsTestId($page, "composer-caption-{$channel->id}");
+ waitFor($page, '@post-composer-dialog');
+ waitFor($page, "@composer-account-{$channel->id}");
+ waitFor($page, "@composer-caption-{$channel->id}");
$page->assertVisible("@composer-account-{$channel->id}")
->assertValue("@composer-caption-{$channel->id}", $url)
diff --git a/tests/Browser/PublishListSkeletonTest.php b/tests/Browser/PublishListSkeletonTest.php
index a251b323e..e9401013a 100644
--- a/tests/Browser/PublishListSkeletonTest.php
+++ b/tests/Browser/PublishListSkeletonTest.php
@@ -12,23 +12,6 @@ use App\Models\User;
use App\Models\Workspace;
use App\Support\PostingSchedule;
-function waitForPublishListSkeletonCondition(mixed $page, string $condition): void
-{
- $page->script(<<<JS
- (async () => {
- for (let attempt = 0; attempt < 100; attempt++) {
- if ({$condition}) return;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })();
- JS);
-}
-
-function waitForPublishListSkeletonTestId(mixed $page, string $testId): void
-{
- waitForPublishListSkeletonCondition($page, "document.querySelector('[data-testid=\"{$testId}\"]')?.getBoundingClientRect().height > 0");
-}
-
/**
* Holds every Inertia partial reload that asks for `posts` until
* `window.__releasePublishList()`.
@@ -134,14 +117,14 @@ test('each tab shows the skeleton, never the empty state, until its cards arrive
$this->actingAs($user);
$page = visit(route('app.posts.index', ['tab' => 'sent']));
- waitForPublishListSkeletonTestId($page, "post-card-{$posts['sent']->id}");
+ waitFor($page, "@post-card-{$posts['sent']->id}");
holdPublishListReloads($page);
foreach (['queue' => 'timeline', 'approvals' => 'list', 'drafts' => 'list', 'sent' => 'list'] as $tab => $variant) {
$post = $posts[$tab];
$page->click("@publish-tab-{$tab}");
- waitForPublishListSkeletonTestId($page, "publish-list-skeleton-{$tab}");
+ waitFor($page, "@publish-list-skeleton-{$tab}");
expect(publishListVisible($page, "publish-list-skeleton-{$tab}"))->toBeTrue()
->and($page->script("document.querySelector('[data-testid=\"publish-list-skeleton-{$tab}\"]').dataset.variant"))->toBe($variant)
@@ -153,7 +136,7 @@ test('each tab shows the skeleton, never the empty state, until its cards arrive
->and($page->script("document.querySelectorAll('[data-testid=\"publish-list-skeleton-slot\"]').length > 0"))->toBe($variant === 'timeline');
$page->script('window.__releasePublishList()');
- waitForPublishListSkeletonTestId($page, "post-card-{$post->id}");
+ waitFor($page, "@post-card-{$post->id}");
$page->assertVisible("@post-card-{$post->id}")
->assertMissing("@publish-list-skeleton-{$tab}")
@@ -172,12 +155,12 @@ test('a tab without data shows its empty state and never the skeleton', function
$this->actingAs($user);
$page = visit($url('drafts'));
- waitForPublishListSkeletonTestId($page, 'publish-empty-new-post-drafts');
+ waitFor($page, '@publish-empty-new-post-drafts');
watchPublishListSkeleton($page);
foreach (['sent', 'queue', 'approvals', 'drafts'] as $tab) {
$page->click("@publish-tab-{$tab}");
- waitForPublishListSkeletonTestId($page, "publish-empty-new-post-{$tab}");
+ waitFor($page, "@publish-empty-new-post-{$tab}");
$page->assertVisible("@publish-empty-new-post-{$tab}")
->assertMissing("@publish-list-skeleton-{$tab}");
@@ -193,21 +176,21 @@ test('the channel queue skeleton is a plain list while the posting times are hid
$this->actingAs($user);
$page = visit(route('app.channels.publish', ['account' => $channel, 'tab' => 'drafts']));
- waitForPublishListSkeletonTestId($page, 'empty-state');
+ waitFor($page, '@empty-state');
setBrowserStorageItem($page, $user, 'publish.showSlots', false);
$page->refresh();
- waitForPublishListSkeletonTestId($page, 'empty-state');
+ waitFor($page, '@empty-state');
$page->click('@publish-tab-sent');
- waitForPublishListSkeletonTestId($page, 'empty-state');
+ waitFor($page, '@empty-state');
holdPublishListReloads($page);
$page->click('@publish-tab-queue');
- waitForPublishListSkeletonTestId($page, 'publish-list-skeleton-queue');
+ waitFor($page, '@publish-list-skeleton-queue');
expect($page->script("document.querySelector('[data-testid=\"publish-list-skeleton-queue\"]').dataset.variant"))->toBe('list')
->and(publishListVisible($page, 'empty-state'))->toBeFalse();
$page->script('window.__releasePublishList()');
- waitForPublishListSkeletonTestId($page, "post-card-{$post->id}");
+ waitFor($page, "@post-card-{$post->id}");
$page->assertVisible("@post-card-{$post->id}")->assertNoJavaScriptErrors();
});
@@ -222,7 +205,7 @@ test('the deferred list keeps appending pages on scroll', function () {
$this->actingAs($user);
$page = visit(route('app.posts.index', ['tab' => 'drafts']));
- waitForPublishListSkeletonCondition($page, "document.querySelectorAll('[data-testid^=\"post-card-\"][data-post-id]').length >= {$perPage}");
+ waitForCount($page, '[data-testid^="post-card-"][data-post-id]', $perPage, '>=');
expect($page->script("document.querySelectorAll('[data-testid^=\"post-card-\"][data-post-id]').length"))->toBe($perPage);
@@ -232,7 +215,7 @@ test('the deferred list keeps appending pages on scroll', function () {
scroller.scrollTop = scroller.scrollHeight;
})();
JS);
- waitForPublishListSkeletonCondition($page, "document.querySelectorAll('[data-testid^=\"post-card-\"][data-post-id]').length > {$perPage}");
+ waitForCount($page, '[data-testid^="post-card-"][data-post-id]', $perPage, '>');
expect($page->script("document.querySelectorAll('[data-testid^=\"post-card-\"][data-post-id]').length"))->toBe($perPage + 3);
$page->assertMissing('@publish-list-skeleton-drafts')->assertNoJavaScriptErrors();
@@ -245,17 +228,17 @@ test('deleting a draft keeps the list on screen without the skeleton', function
$this->actingAs($user);
$page = visit(route('app.posts.index', ['tab' => 'drafts']));
- waitForPublishListSkeletonTestId($page, "post-card-{$deleted->id}");
+ waitFor($page, "@post-card-{$deleted->id}");
watchPublishListSkeleton($page);
$page->click("@post-card-menu-{$deleted->id}");
- waitForPublishListSkeletonTestId($page, "post-delete-{$deleted->id}");
+ waitFor($page, "@post-delete-{$deleted->id}");
$page->click("@post-delete-{$deleted->id}");
- waitForPublishListSkeletonTestId($page, 'confirm-delete-action');
+ waitFor($page, '@confirm-delete-action');
$page->assertMissing('@confirm-delete-input')
->assertSeeIn('@confirm-delete-action', __('posts.edit.delete_modal.action'))
->click('@confirm-delete-action');
- waitForPublishListSkeletonCondition($page, "document.querySelector('[data-testid=\"post-card-{$deleted->id}\"]') === null");
+ waitForGone($page, "@post-card-{$deleted->id}");
expect($page->script('window.__publishSkeletonSeen'))->toBeFalse()
->and(Post::query()->whereKey($deleted->id)->exists())->toBeFalse();
diff --git a/tests/Browser/PublishPageTest.php b/tests/Browser/PublishPageTest.php
index e0c815458..583a99551 100644
--- a/tests/Browser/PublishPageTest.php
+++ b/tests/Browser/PublishPageTest.php
@@ -215,14 +215,8 @@ test('saving a queued post edited on a channel page returns to that page and tab
waitFor($page, '@composer-submit');
$page->click('@composer-submit');
- $page->script(<<<'JS'
- (async () => {
- for (let attempt = 0; attempt < 100; attempt++) {
- if (!new URLSearchParams(location.search).has('edit') && !document.querySelector('[data-testid="post-composer-dialog"]')) return;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })();
- JS);
+ waitForCondition($page, "!new URLSearchParams(location.search).has('edit')");
+ waitForGone($page, '@post-composer-dialog');
waitFor($page, "@post-card-{$queued->id}");
expect($page->script('location.pathname'))->toBe(route('app.channels.publish', $channel, absolute: false))
@@ -430,7 +424,7 @@ test('the calendar keeps its filters in one menu until the screen is wide enough
$page->click('@calendar-menu');
waitFor($page, '@calendar-menu-content');
- waitForCondition($page, 'Math.abs(window.innerHeight - document.querySelector(\'[data-testid="calendar-menu-content"]\').getBoundingClientRect().bottom) <= 1');
+ waitForState($page, '@calendar-menu-content', 'Math.abs(window.innerHeight - element.getBoundingClientRect().bottom) <= 1');
$page->assertVisible('@calendar-status-drafts')
->assertVisible('@publish-timezone-trigger')
@@ -450,8 +444,8 @@ test('the calendar keeps its filters in one menu until the screen is wide enough
$page->assertMissing('@calendar-undated-panel');
$page->resize(900, 900);
- waitForCondition($page, 'Boolean(document.querySelector(\'[data-testid="posts-label-filter"]\')?.getClientRects().length)');
- waitForCondition($page, '!document.querySelector(\'[data-testid="calendar-status-filter"]\')');
+ waitForState($page, '@posts-label-filter', 'Boolean(element.getClientRects().length)');
+ waitForGone($page, '@calendar-status-filter');
expect($page->script('Boolean(document.querySelector(\'[data-testid="calendar-status-filter"]\'))'))->toBeFalse()
->and($page->script('Boolean(document.querySelector(\'[data-testid="calendar-menu"]\')?.getClientRects().length)'))->toBeTrue()
@@ -459,7 +453,7 @@ test('the calendar keeps its filters in one menu until the screen is wide enough
$page->resize(1600, 900);
- waitForCondition($page, 'Boolean(document.querySelector(\'[data-testid="calendar-status-filter"]\'))');
+ waitForState($page, '@calendar-status-filter', 'true');
$order = $page->script(<<<'JS'
(() => ['posts-channel-filter', 'posts-label-filter', 'calendar-status-filter', 'publish-timezone-trigger', 'calendar-no-date', 'calendar-menu']
@@ -505,7 +499,7 @@ test('the channel page adapts its filters, tabs, calendar link and notes button
$page->resize(390, 844);
waitFor($page, '@publish-tabs-mobile-trigger');
- waitForCondition($page, '!document.querySelector(\'[data-testid="posts-label-filter"]\')');
+ waitForGone($page, '@posts-label-filter');
$phone = $page->script(<<<'JS'
(() => {
@@ -528,7 +522,7 @@ test('the channel page adapts its filters, tabs, calendar link and notes button
$page->click('@publish-menu');
waitFor($page, '@publish-menu-content');
- waitForCondition($page, 'Math.abs(window.innerHeight - document.querySelector(\'[data-testid="publish-menu-content"]\').getBoundingClientRect().bottom) <= 1');
+ waitForState($page, '@publish-menu-content', 'Math.abs(window.innerHeight - element.getBoundingClientRect().bottom) <= 1');
$pressed = 'document.querySelector(\'[data-testid="publish-toggle-slots"]\').getAttribute("aria-pressed")';
$before = $page->script($pressed);
@@ -540,7 +534,7 @@ test('the channel page adapts its filters, tabs, calendar link and notes button
->toBe(route('app.channels.settings', $channel, false));
$page->resize(1280, 800);
- waitForCondition($page, '!document.querySelector(\'[data-testid="publish-menu-content"]\')');
+ waitForGone($page, '@publish-menu-content');
waitFor($page, '@publish-timezone-trigger');
$desktop = $page->script(<<<'JS'
@@ -573,7 +567,7 @@ test('the channel page adapts its filters, tabs, calendar link and notes button
$page->assertPresent('@publish-tab-sheet-queue-check')
->assertMissing('@publish-tab-sheet-drafts-check')
->click('@publish-tab-sheet-drafts');
- waitForCondition($page, 'new URLSearchParams(location.search).get("tab") === "drafts"');
+ waitForQueryParameter($page, 'tab', 'drafts');
$page->assertSeeIn('@publish-tabs-mobile-trigger', trans('posts.publish.tabs.drafts'))
->assertMissing('@publish-tabs-sheet');
diff --git a/tests/Browser/PublishQueueTest.php b/tests/Browser/PublishQueueTest.php
index c85ae5bb0..b3e22d257 100644
--- a/tests/Browser/PublishQueueTest.php
+++ b/tests/Browser/PublishQueueTest.php
@@ -18,35 +18,9 @@ use App\Models\Workspace;
use App\Support\PostingSchedule;
use Carbon\CarbonInterface;
-function waitForPublishQueueTestId(mixed $page, string $testId): void
-{
- $page->script(<<<JS
- (async () => {
- for (let attempt = 0; attempt < 100; attempt++) {
- if (document.querySelector('[data-testid="{$testId}"]')?.getBoundingClientRect().height > 0) return;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })();
- JS);
-}
-
-function waitForPublishQueueCondition(mixed $page, string $condition): void
-{
- $page->script(<<<JS
- (async () => {
- for (let attempt = 0; attempt < 100; attempt++) {
- if ({$condition}) return;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })();
- JS);
-}
-
function waitForPublishQueueOrder(mixed $page, Post $first, Post $second): void
{
- for ($attempt = 0; $attempt < 50 && ! $first->refresh()->scheduled_at->lessThan($second->refresh()->scheduled_at); $attempt++) {
- $page->script('new Promise((resolve) => setTimeout(resolve, 100))');
- }
+ waitForDatabase($page, fn () => $first->refresh()->scheduled_at->lessThan($second->refresh()->scheduled_at));
}
/**
@@ -113,22 +87,22 @@ test('a slot opens the composer at that slot and saving places the post there as
$this->actingAs($user);
$page = visit(route('app.posts.index'));
- waitForPublishQueueTestId($page, "queue-slot-{$slotKey}");
+ waitFor($page, "@queue-slot-{$slotKey}");
$page->assertVisible("@queue-day-{$slot->utc()->format('Y-m-d')}")
->assertVisible("@queue-slot-{$slotKey}")
->click("@queue-slot-new-{$slotKey}");
- waitForPublishQueueTestId($page, "composer-caption-{$channel->id}");
+ waitFor($page, "@composer-caption-{$channel->id}");
$page->fill("@composer-caption-{$channel->id}", 'From an empty slot');
- waitForPublishQueueTestId($page, 'composer-submit');
+ waitFor($page, '@composer-submit');
$label = $slot->format($slot->year === now('UTC')->year ? 'M j' : 'M j, Y').", {$slot->format('H:i')}";
expect($page->script('document.querySelector(\'[data-testid="composer-submit"]\').dataset.scheduleMode'))->toBe('custom')
->and(trim((string) $page->script('document.querySelector("[data-testid=composer-schedule-trigger]").textContent')))->toBe($label);
$page->click('@composer-submit');
- waitForPublishQueueCondition($page, '!document.querySelector(\'[data-testid="post-composer-dialog"]\')');
+ waitForGone($page, '@post-composer-dialog');
$post = Post::query()->where('workspace_id', $channel->workspace_id)->sole();
@@ -146,7 +120,7 @@ test('a member whose posts need approval can still open the composer from an emp
$this->actingAs($requester);
$page = visit(route('app.posts.index'));
- waitForPublishQueueTestId($page, "queue-slot-new-{$slotKey}");
+ waitFor($page, "@queue-slot-new-{$slotKey}");
expect($page->script("(() => { const slot = document.querySelector('[data-testid=\"queue-slot-new-{$slotKey}\"]'); const icon = slot.querySelector('svg[data-testid=\"queue-slot-icon-{$slotKey}\"]'); return [icon !== null, slot.querySelector('img') === null, icon && getComputedStyle(icon).color]; })()"))
->toBe([true, true, 'rgb(10, 102, 194)']);
@@ -154,7 +128,7 @@ test('a member whose posts need approval can still open the composer from an emp
$page->assertSeeIn("@queue-slot-new-{$slotKey}", 'New')
->click("@queue-slot-new-{$slotKey}");
- waitForPublishQueueTestId($page, "composer-caption-{$channel->id}");
+ waitFor($page, "@composer-caption-{$channel->id}");
$page->assertVisible("@composer-caption-{$channel->id}")
->assertNoJavaScriptErrors();
});
@@ -171,7 +145,7 @@ test('scheduled posts replace the slots with a list of only those posts', functi
$this->actingAs($user);
$page = publishQueueVisitWithCleanStorage(route('app.posts.index'));
- waitForPublishQueueTestId($page, "post-card-{$custom->id}");
+ waitFor($page, "@post-card-{$custom->id}");
$page->assertVisible("@post-card-{$queued->id}")
->assertPresent("@queue-day-{$custom->scheduled_at->format('Y-m-d')}")
@@ -190,9 +164,9 @@ test('move down from the card menu swaps a queued post with the next one', funct
$this->actingAs($user);
$page = visit(route('app.channels.publish', $channel));
- waitForPublishQueueTestId($page, "post-card-menu-{$a->id}");
+ waitFor($page, "@post-card-menu-{$a->id}");
$page->click("@post-card-menu-{$a->id}");
- waitForPublishQueueTestId($page, "post-move-down-{$a->id}");
+ waitFor($page, "@post-move-down-{$a->id}");
$page->click("@post-move-down-{$a->id}");
waitForPublishQueueOrder($page, $b, $a);
@@ -207,7 +181,7 @@ test('dragging a queued post above another reorders the queue', function () {
$this->actingAs($user);
$page = visit(route('app.channels.publish', $channel));
- waitForPublishQueueTestId($page, "post-drag-handle-{$b->id}");
+ waitFor($page, "@post-drag-handle-{$b->id}");
$page->drag("@post-card-{$b->id}", "@post-card-{$a->id}");
waitForPublishQueueOrder($page, $b, $a);
@@ -222,15 +196,15 @@ test('a stale reorder is rolled back and reported', function () {
$this->actingAs($user);
$page = visit(route('app.channels.publish', $channel));
- waitForPublishQueueTestId($page, "post-card-menu-{$a->id}");
+ waitFor($page, "@post-card-menu-{$a->id}");
$top = publishQueuePost($user, $channel, QueuePosition::Top);
$page->click("@post-card-menu-{$a->id}");
- waitForPublishQueueTestId($page, "post-move-down-{$a->id}");
+ waitFor($page, "@post-move-down-{$a->id}");
$page->click("@post-move-down-{$a->id}");
- waitForPublishQueueTestId($page, 'queue-reorder-error-toast');
+ waitFor($page, '@queue-reorder-error-toast');
$page->assertSeeIn('@queue-reorder-error-toast', __('posts.errors.queue_order_stale'));
- waitForPublishQueueTestId($page, "post-card-{$top->id}");
+ waitFor($page, "@post-card-{$top->id}");
$page->assertVisible("@post-card-{$top->id}");
expect($page->script("document.querySelector('[data-post-id=\"{$a->id}\"]').compareDocumentPosition(document.querySelector('[data-post-id=\"{$b->id}\"]')) & Node.DOCUMENT_POSITION_FOLLOWING"))->toBeGreaterThan(0)
->and($a->refresh()->scheduled_at->lessThan($b->refresh()->scheduled_at))->toBeTrue();
@@ -245,17 +219,17 @@ test('the posting times toggle hides every slot and survives a reload', function
$this->actingAs($user);
$page = publishQueueVisitWithCleanStorage(route('app.channels.publish', $channel));
- waitForPublishQueueTestId($page, "queue-slot-{$slotKey}");
+ waitFor($page, "@queue-slot-{$slotKey}");
$page->click('@publish-menu');
- waitForPublishQueueTestId($page, 'publish-toggle-slots');
+ waitFor($page, '@publish-toggle-slots');
$page->click('@publish-toggle-slots');
- waitForPublishQueueCondition($page, '!document.querySelector(\'[data-testid^="queue-slot-"]\')');
+ waitForGone($page, '[data-testid^="queue-slot-"]');
expect($page->script('document.querySelectorAll(\'[data-testid^="queue-slot-"]\').length'))->toBe(0);
$page->assertVisible("@post-card-{$queued->id}");
$page->refresh();
- waitForPublishQueueTestId($page, "post-card-{$queued->id}");
+ waitFor($page, "@post-card-{$queued->id}");
expect($page->script('document.querySelectorAll(\'[data-testid^="queue-slot-"]\').length'))->toBe(0);
$page->assertVisible("@post-card-{$queued->id}")
@@ -271,16 +245,16 @@ test('a far display time zone regroups slots under its own calendar day', functi
$this->actingAs($user);
$page = publishQueueVisitWithCleanStorage(route('app.posts.index'));
- waitForPublishQueueTestId($page, "queue-slot-{$slotKey}");
+ waitFor($page, "@queue-slot-{$slotKey}");
expect($page->script("!!document.querySelector('[data-testid=\"queue-day-{$utcDay}\"] [data-testid=\"queue-slot-{$slotKey}\"]')"))->toBeTrue();
$page->click('@publish-timezone-trigger');
- waitForPublishQueueTestId($page, 'publish-timezone-search');
+ waitFor($page, '@publish-timezone-search');
$page->type('@publish-timezone-search', 'Auckland');
- waitForPublishQueueTestId($page, 'publish-timezone-option-Pacific-Auckland');
+ waitFor($page, '@publish-timezone-option-Pacific-Auckland');
$page->click('@publish-timezone-option-Pacific-Auckland');
- waitForPublishQueueCondition($page, "!!document.querySelector('[data-testid=\"queue-day-{$aucklandDay}\"] [data-testid=\"queue-slot-{$slotKey}\"]')");
+ waitForState($page, "@queue-day-{$aucklandDay} @queue-slot-{$slotKey}", 'true');
expect($page->script('new URLSearchParams(location.search).get("tz")'))->toBe('Pacific/Auckland')
->and($page->script("!!document.querySelector('[data-testid=\"queue-day-{$aucklandDay}\"] [data-testid=\"queue-slot-{$slotKey}\"]')"))->toBeTrue();
@@ -294,9 +268,9 @@ test('the time zone picked for the list is kept in the browser and shown again o
$page = publishQueueVisitWithCleanStorage(route('app.posts.index'));
waitFor($page, '@publish-timezone-trigger');
$page->click('@publish-timezone-trigger');
- waitForPublishQueueTestId($page, 'publish-timezone-search');
+ waitFor($page, '@publish-timezone-search');
$page->type('@publish-timezone-search', 'Auckland');
- waitForPublishQueueTestId($page, 'publish-timezone-option-Pacific-Auckland');
+ waitFor($page, '@publish-timezone-option-Pacific-Auckland');
$page->click('@publish-timezone-option-Pacific-Auckland');
waitForQueryParameter($page, 'tz', 'Pacific/Auckland');
@@ -322,16 +296,16 @@ test('changing the time zone keeps a tab that came from a notes link', function
$this->actingAs($user);
$page = publishQueueVisitWithCleanStorage(route('app.posts.index', ['notes' => $draft->id]));
- waitForPublishQueueTestId($page, "post-card-{$draft->id}");
+ waitFor($page, "@post-card-{$draft->id}");
$page->script("document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }))");
$page->click('@publish-timezone-trigger');
- waitForPublishQueueTestId($page, 'publish-timezone-search');
+ waitFor($page, '@publish-timezone-search');
$page->type('@publish-timezone-search', 'Auckland');
- waitForPublishQueueTestId($page, 'publish-timezone-option-Pacific-Auckland');
+ waitFor($page, '@publish-timezone-option-Pacific-Auckland');
$page->click('@publish-timezone-option-Pacific-Auckland');
- waitForPublishQueueCondition($page, 'new URLSearchParams(location.search).get("tz") === "Pacific/Auckland"');
- waitForPublishQueueTestId($page, "post-card-{$draft->id}");
+ waitForQueryParameter($page, 'tz', 'Pacific/Auckland');
+ waitFor($page, "@post-card-{$draft->id}");
expect($page->script('new URLSearchParams(location.search).get("tab")'))->toBe('drafts')
->and($page->script('new URLSearchParams(location.search).has("notes")'))->toBeFalse();
@@ -344,10 +318,10 @@ test('more times extends the queue range', function () {
$this->actingAs($user);
$page = visit(route('app.posts.index'));
- waitForPublishQueueTestId($page, 'queue-more-times');
+ waitFor($page, '@queue-more-times');
$page->assertMissing("@queue-day-{$farDay}")
->click('@queue-more-times');
- waitForPublishQueueTestId($page, "queue-day-{$farDay}");
+ waitFor($page, "@queue-day-{$farDay}");
$page->assertPresent("@queue-day-{$farDay}")
->assertNoJavaScriptErrors();
@@ -364,7 +338,7 @@ test('a failed post is listed in sent with its failed badge and actions', functi
$this->actingAs($user);
$page = visit(route('app.posts.index', ['tab' => 'sent']));
- waitForPublishQueueTestId($page, "post-card-{$failed->id}");
+ waitFor($page, "@post-card-{$failed->id}");
$page->assertSeeIn("@post-status-{$failed->id}", __('posts.status.failed'))
->assertSeeIn("@post-created-by-{$failed->id}", $user->name)
@@ -375,16 +349,16 @@ test('a failed post is listed in sent with its failed badge and actions', functi
->toStartWith($failed->scheduled_at->toDateString());
$page->click("@post-status-{$failed->id}");
- waitForPublishQueueTestId($page, "post-failure-{$failed->id}");
+ waitFor($page, "@post-failure-{$failed->id}");
$page->assertSeeIn("@post-failure-reason-{$failed->id}", __('posts.publish.failure.categories.media_format'))
->assertSeeIn("@post-failure-details-{$failed->id}", 'Video duration exceeds the 90 second limit.');
$page->script("document.dispatchEvent(new KeyboardEvent('keydown', {key: 'Escape', bubbles: true}))");
- waitForPublishQueueCondition($page, "!document.querySelector('[data-testid=\"post-failure-{$failed->id}\"]')");
+ waitForGone($page, "@post-failure-{$failed->id}");
$page->click("@post-card-menu-{$failed->id}");
- waitForPublishQueueTestId($page, "post-duplicate-{$failed->id}");
+ waitFor($page, "@post-duplicate-{$failed->id}");
$page->assertPresent("@post-duplicate-{$failed->id}")
->assertPresent("@post-details-open-{$failed->id}")
@@ -412,9 +386,7 @@ function publishQueueFollows(mixed $page, string $firstTestId, string $secondTes
function waitForPublishQueueMode(mixed $page, Post $post, ScheduleMode $mode): void
{
- for ($attempt = 0; $attempt < 50 && $post->refresh()->schedule_mode !== $mode; $attempt++) {
- $page->script('new Promise((resolve) => setTimeout(resolve, 100))');
- }
+ waitForDatabase($page, fn () => $post->refresh()->schedule_mode === $mode);
}
test('a scheduled post sits between the free posting times and its drag handle shows in the gutter on hover', function () {
@@ -425,8 +397,8 @@ test('a scheduled post sits between the free posting times and its drag handle s
$this->actingAs($user);
$page = publishQueueVisitWithCleanStorage(route('app.channels.publish', $channel));
- waitForPublishQueueTestId($page, "post-time-{$queued->id}");
- waitForPublishQueueTestId($page, "queue-slot-{$nextFreeKey}");
+ waitFor($page, "@post-time-{$queued->id}");
+ waitFor($page, "@queue-slot-{$nextFreeKey}");
$page->assertVisible("@post-card-{$queued->id}")
->assertVisible("@queue-slot-{$nextFreeKey}")
@@ -441,7 +413,7 @@ test('a scheduled post sits between the free posting times and its drag handle s
expect($page->script("getComputedStyle({$handle}).opacity"))->toBe('0');
$page->hover("@post-time-{$queued->id}");
- waitForPublishQueueCondition($page, "getComputedStyle({$handle}).opacity === '1'");
+ waitForState($page, "@post-drag-handle-{$queued->id}", "getComputedStyle(element).opacity === '1'");
expect($page->script("getComputedStyle({$handle}).opacity"))->toBe('1')
->and($page->script("{$handle}.getBoundingClientRect().left >= {$time}.getBoundingClientRect().right"))->toBeTrue()
@@ -460,14 +432,14 @@ test('dragging a post with its own time onto a free slot queues it at that slot'
$this->actingAs($user);
$page = publishQueueVisitWithCleanStorage(route('app.channels.publish', $channel));
- waitForPublishQueueTestId($page, "post-drag-handle-{$custom->id}");
- waitForPublishQueueTestId($page, "queue-slot-{$targetKey}");
+ waitFor($page, "@post-drag-handle-{$custom->id}");
+ waitFor($page, "@queue-slot-{$targetKey}");
$page->drag("@post-card-{$custom->id}", "@queue-slot-{$targetKey}");
waitForPublishQueueMode($page, $custom, ScheduleMode::Queue);
expect($custom->refresh()->schedule_mode)->toBe(ScheduleMode::Queue)
->and($custom->scheduled_at->equalTo($slots[2]))->toBeTrue();
- waitForPublishQueueCondition($page, "!document.querySelector('[data-testid=\"queue-slot-{$targetKey}\"]')");
+ waitForGone($page, "@queue-slot-{$targetKey}");
$page->assertMissing("@queue-slot-{$targetKey}")
->assertNoJavaScriptErrors();
});
@@ -481,11 +453,11 @@ test('dropping a post on a slot taken meanwhile is rolled back and reported', fu
$this->actingAs($user);
$page = publishQueueVisitWithCleanStorage(route('app.channels.publish', $channel));
- waitForPublishQueueTestId($page, "queue-slot-{$targetKey}");
- waitForPublishQueueTestId($page, "post-drag-handle-{$custom->id}");
+ waitFor($page, "@queue-slot-{$targetKey}");
+ waitFor($page, "@post-drag-handle-{$custom->id}");
publishQueuePost($user, $channel);
$page->drag("@post-card-{$custom->id}", "@queue-slot-{$targetKey}");
- waitForPublishQueueTestId($page, 'queue-reorder-error-toast');
+ waitFor($page, '@queue-reorder-error-toast');
$page->assertSeeIn('@queue-reorder-error-toast', __('posts.errors.queue_order_stale'));
expect($custom->refresh()->schedule_mode)->toBe(ScheduleMode::Custom)
@@ -504,18 +476,16 @@ test('dragging a queued post onto a later free slot keeps it there and leaves th
$this->actingAs($user);
$page = publishQueueVisitWithCleanStorage(route('app.channels.publish', $channel));
- waitForPublishQueueTestId($page, "queue-slot-{$targetKey}");
- waitForPublishQueueTestId($page, "post-card-{$first->id}");
+ waitFor($page, "@queue-slot-{$targetKey}");
+ waitFor($page, "@post-card-{$first->id}");
$page->drag("@post-card-{$first->id}", "@queue-slot-{$targetKey}");
- for ($attempt = 0; $attempt < 50 && ! $first->refresh()->scheduled_at->equalTo($slots[3]); $attempt++) {
- $page->script('new Promise((resolve) => setTimeout(resolve, 100))');
- }
+ waitForDatabase($page, fn () => $first->refresh()->scheduled_at->equalTo($slots[3]));
expect($first->refresh()->scheduled_at->equalTo($slots[3]))->toBeTrue()
->and($first->schedule_mode)->toBe(ScheduleMode::Queue)
->and($second->refresh()->scheduled_at->equalTo($secondAt))->toBeTrue();
- waitForPublishQueueTestId($page, 'queue-slot-'.publishQueueSlotKey($channel, $slots[0]));
+ waitFor($page, '@queue-slot-'.publishQueueSlotKey($channel, $slots[0]));
$page->assertPresent('@queue-slot-'.publishQueueSlotKey($channel, $slots[0]))
->assertNoJavaScriptErrors();
});
@@ -531,8 +501,8 @@ test('free slots follow the loaded posts beyond the default range', function ()
$this->actingAs($user);
$page = publishQueueVisitWithCleanStorage(route('app.channels.publish', $channel));
- waitForPublishQueueTestId($page, "post-card-{$far->id}");
- waitForPublishQueueCondition($page, "!!document.querySelector('[data-testid=\"queue-slot-{$slotKey}\"]')");
+ waitFor($page, "@post-card-{$far->id}");
+ waitForState($page, "@queue-slot-{$slotKey}", 'true');
$page->assertPresent("@queue-slot-{$slotKey}");
expect(publishQueueFollows($page, "queue-slot-{$slotKey}", "post-card-{$far->id}"))->toBeTrue();
@@ -546,7 +516,7 @@ test('the all channels queue keeps its drag handle inline before the time', func
$this->actingAs($user);
$page = publishQueueVisitWithCleanStorage(route('app.posts.index'));
- waitForPublishQueueTestId($page, "post-drag-handle-{$first->id}");
+ waitFor($page, "@post-drag-handle-{$first->id}");
$handle = "document.querySelector('[data-testid=\"post-drag-handle-{$first->id}\"]')";
$time = "document.querySelector('[data-testid=\"post-time-{$first->id}\"]')";
@@ -582,7 +552,7 @@ test('a pending queue request shows at its reserved slot and approving it keeps
$this->actingAs($user);
$page = publishQueueVisitWithCleanStorage(route('app.channels.publish', $channel));
- waitForPublishQueueTestId($page, "post-card-{$pending->id}");
+ waitFor($page, "@post-card-{$pending->id}");
$page->assertVisible("@post-approval-badge-{$pending->id}")
->assertVisible("@post-approve-{$pending->id}")
@@ -596,12 +566,12 @@ test('a pending queue request shows at its reserved slot and approving it keeps
->and(publishQueueFollows($page, 'queue-slot-'.publishQueueSlotKey($channel, $first), "post-card-{$pending->id}"))->toBeTrue();
$page->click("@post-approve-{$pending->id}");
- waitForPublishQueueCondition($page, "!document.querySelector('[data-testid=\"post-approval-badge-{$pending->id}\"]')");
+ waitForGone($page, "@post-approval-badge-{$pending->id}");
expect($pending->refresh()->status)->toBe(PostStatus::Scheduled)
->and($pending->scheduled_at->equalTo($reserved))->toBeTrue();
- waitForPublishQueueTestId($page, "post-card-{$pending->id}");
+ waitFor($page, "@post-card-{$pending->id}");
$page->assertVisible("@post-card-{$pending->id}")
->assertMissing("@post-approval-badge-{$pending->id}")
->assertPresent("@post-drag-handle-{$pending->id}")
@@ -626,7 +596,7 @@ test('a publishing post waiting for a network limit shows when it retries', func
$this->actingAs($user);
$page = visit(route('app.posts.index'));
- waitForPublishQueueTestId($page, "post-limit-retry-{$waiting->id}");
+ waitFor($page, "@post-limit-retry-{$waiting->id}");
$page->assertVisible("@post-publishing-{$waiting->id}")
->assertSeeIn("@post-limit-retry-{$waiting->id}", __('posts.publish.retrying_at', ['time' => $retryAt->utc()->format('H:i')]))
@@ -646,7 +616,7 @@ test('a google business post waiting for review says google is reviewing it', fu
$this->actingAs($user);
$page = visit(route('app.posts.index'));
- waitForPublishQueueTestId($page, "post-google-review-{$inReview->id}");
+ waitFor($page, "@post-google-review-{$inReview->id}");
$page->assertSeeIn("@post-google-review-{$inReview->id}", __('posts.publish.in_google_review'))
->assertNotPresent("@post-publishing-progress-{$inReview->id}")
@@ -667,7 +637,7 @@ test('a publishing post sits in its own queue group and moves to sent once it se
$this->actingAs($user);
$page = visit(route('app.posts.index'));
- waitForPublishQueueTestId($page, "post-publishing-{$publishing->id}");
+ waitFor($page, "@post-publishing-{$publishing->id}");
$page->assertVisible('@queue-publishing')
->assertVisible("@post-publishing-{$publishing->id}")
@@ -695,7 +665,7 @@ test('a publishing post sits in its own queue group and moves to sent once it se
window.Pusher.instances[0].channels.channels['private-workspace.{$workspace->id}']
.emit('post.platform.status.updated', { post_id: '{$publishing->id}' });
JS);
- waitForPublishQueueCondition($page, '!document.querySelector(\'[data-testid="queue-publishing"]\')');
+ waitForGone($page, '@queue-publishing');
$page->assertMissing('@queue-publishing')
->assertMissing("@post-card-{$publishing->id}")
@@ -703,7 +673,7 @@ test('a publishing post sits in its own queue group and moves to sent once it se
->assertSeeIn('@publish-tab-count-queue', '1');
$page->click('@publish-tab-sent');
- waitForPublishQueueTestId($page, "post-card-{$publishing->id}");
+ waitFor($page, "@post-card-{$publishing->id}");
$page->assertVisible("@post-card-{$publishing->id}")
->assertNoJavaScriptErrors();
diff --git a/tests/Browser/ReferralSourceSurveyTest.php b/tests/Browser/ReferralSourceSurveyTest.php
index b1234f828..0bc1ba408 100644
--- a/tests/Browser/ReferralSourceSurveyTest.php
+++ b/tests/Browser/ReferralSourceSurveyTest.php
@@ -6,31 +6,9 @@ use App\Enums\User\ReferralSource;
use App\Models\User;
use App\Models\Workspace;
-function waitForReferralSurveyCondition(mixed $page, string $condition): void
-{
- $page->script(<<<JS
- (async () => {
- for (let attempt = 0; attempt < 200; attempt++) {
- if ({$condition}) return;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })();
- JS);
-}
-
-function waitForReferralSurveyTestIdPresent(mixed $page, string $testId): void
-{
- waitForReferralSurveyCondition($page, "document.querySelector('[data-testid=\"{$testId}\"]')");
-}
-
-function waitForReferralSurveyTestIdGone(mixed $page, string $testId): void
-{
- waitForReferralSurveyCondition($page, "!document.querySelector('[data-testid=\"{$testId}\"]')");
-}
-
function waitForReferralSurveySheetAtBottom(mixed $page): void
{
- waitForReferralSurveyCondition($page, "(() => { const sheet = document.querySelector('[data-testid=\"referral-source-survey\"]'); return sheet && Math.abs(window.innerHeight - sheet.getBoundingClientRect().bottom) < 1; })()");
+ waitForState($page, '@referral-source-survey', 'Math.abs(window.innerHeight - element.getBoundingClientRect().bottom) < 1');
}
/**
@@ -63,13 +41,13 @@ test('a user who has not said where they found us answers from the in-app card',
$this->actingAs($user->fresh());
$page = visit(route('app.calendar'))->resize(1280, 900);
- waitForReferralSurveyTestIdPresent($page, 'referral-source-survey');
+ waitForState($page, '@referral-source-survey', 'true');
$page->assertButtonDisabled('@referral-source-submit');
$page->click('@referral-source-option-'.ReferralSource::ProductHunt->value)
->click('@referral-source-submit');
- waitForReferralSurveyTestIdGone($page, 'referral-source-survey');
+ waitForGone($page, '@referral-source-survey');
$page->assertMissing('@referral-source-survey')
->assertNoJavaScriptErrors();
@@ -98,7 +76,7 @@ test('on a phone the survey slides up as a bottom sheet and can be answered', fu
$page->click('@referral-source-option-google')
->click('@referral-source-submit');
- waitForReferralSurveyTestIdGone($page, 'referral-source-survey');
+ waitForGone($page, '@referral-source-survey');
expect($user->fresh()->referral_source)->toBe(ReferralSource::Google);
$page->assertNoJavaScriptErrors();
diff --git a/tests/Browser/RepurposeAccountHealthTest.php b/tests/Browser/RepurposeAccountHealthTest.php
index 2314a29fb..6077c00bc 100644
--- a/tests/Browser/RepurposeAccountHealthTest.php
+++ b/tests/Browser/RepurposeAccountHealthTest.php
@@ -11,20 +11,6 @@ use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
-function waitForRepurposeHealthTestId(mixed $page, string $testId): void
-{
- $page->script(<<<JS
- (async () => {
- const sel = '[data-testid="{$testId}"]';
- for (let i = 0; i < 100; i++) {
- const el = document.querySelector(sel);
- if (el && el.getBoundingClientRect().height > 0) return;
- await new Promise((r) => setTimeout(r, 50));
- }
- })();
- JS);
-}
-
test('a repurpose whose source was deleted explains itself instead of rendering a hole', function () {
$user = User::factory()->create();
$workspace = Workspace::factory()->create([
@@ -52,7 +38,7 @@ test('a repurpose whose source was deleted explains itself instead of rendering
$page = visit(route('app.repurposes.show', $repurpose));
- waitForRepurposeHealthTestId($page, 'repurpose-health-banner');
+ waitFor($page, '@repurpose-health-banner');
$page->assertSee(__('repurposes.health.source_missing'))
->assertSee(__('repurposes.summary.no_source'))
diff --git a/tests/Browser/RepurposeTest.php b/tests/Browser/RepurposeTest.php
index 55756aeb0..c82b7b09b 100644
--- a/tests/Browser/RepurposeTest.php
+++ b/tests/Browser/RepurposeTest.php
@@ -25,32 +25,6 @@ beforeEach(function () {
Queue::fake([BootstrapAccountAnalytics::class, CollectAccountDailySnapshot::class]);
});
-function waitForRepurposeTestId(mixed $page, string $testId): void
-{
- $page->script(<<<JS
- (async () => {
- const sel = '[data-testid="{$testId}"]';
- for (let i = 0; i < 100; i++) {
- const el = document.querySelector(sel);
- if (el && el.getBoundingClientRect().height > 0) return;
- await new Promise((r) => setTimeout(r, 50));
- }
- })();
- JS);
-}
-
-function waitForRepurposeCondition(mixed $page, string $condition): void
-{
- $page->script(<<<JS
- (async () => {
- for (let i = 0; i < 100; i++) {
- if ({$condition}) return;
- await new Promise((r) => setTimeout(r, 50));
- }
- })();
- JS);
-}
-
function repurposeOwnerWithAccounts(): array
{
$user = User::factory()->create();
@@ -86,7 +60,7 @@ test('the edit page shows the watched format, the destinations and the settings
$page = visit(route('app.repurposes.show', $repurpose));
- waitForRepurposeTestId($page, 'source-format-select');
+ waitFor($page, '@source-format-select');
$page->assertRoute('app.repurposes.show', ['repurpose' => $repurpose->id])
->assertVisible('@repurpose-summary')
@@ -115,7 +89,7 @@ test('a destination is not warned about missing media before there is any', func
$page = visit(route('app.repurposes.show', $repurpose));
- waitForRepurposeTestId($page, "channel-type-{$facebook->id}-facebook_reel");
+ waitFor($page, "@channel-type-{$facebook->id}-facebook_reel");
$page->assertVisible("@channel-settings-{$facebook->id}")
->assertAttribute("@channel-type-{$facebook->id}-facebook_reel", 'aria-checked', 'true')
@@ -142,21 +116,21 @@ test('the source account is picked from a searchable list and handed back to the
$page = visit(route('app.repurposes.show', $repurpose));
- waitForRepurposeTestId($page, 'source-account-select');
+ waitFor($page, '@source-account-select');
$page->assertVisible("@channel-{$facebook->id}")
->assertMissing("@channel-{$source->id}")
->assertAttribute('@repurpose-source-avatar', 'data-platform', Platform::Instagram->value)
->click('@source-account-select');
- waitForRepurposeTestId($page, "source-option-{$facebook->id}");
+ waitFor($page, "@source-option-{$facebook->id}");
$page->assertSee($facebook->display_name)
->assertVisible("@source-option-disconnected-{$broken->id}")
->assertMissing("@source-option-disconnected-{$source->id}")
->click("@source-option-{$facebook->id}");
- waitForRepurposeTestId($page, "channel-{$source->id}");
+ waitFor($page, "@channel-{$source->id}");
$page->assertVisible("@channel-{$source->id}")
->assertMissing("@channel-{$facebook->id}")
@@ -176,12 +150,12 @@ test('deleting sits behind the menu instead of on the page', function () {
$page = visit(route('app.repurposes.show', $repurpose));
- waitForRepurposeTestId($page, 'repurpose-menu');
+ waitFor($page, '@repurpose-menu');
$page->assertMissing('@delete-repurpose')
->click('@repurpose-menu');
- waitForRepurposeTestId($page, 'delete-repurpose');
+ waitFor($page, '@delete-repurpose');
$page->assertVisible('@delete-repurpose')
->assertNoJavaScriptErrors();
@@ -206,11 +180,11 @@ test('the activity list reads as what happened, never as a database id', functio
$page = visit(route('app.repurposes.show', $repurpose));
- waitForRepurposeTestId($page, 'tab-activity');
+ waitFor($page, '@tab-activity');
$page->click('@tab-activity');
- waitForRepurposeTestId($page, "repurpose-item-{$withoutLink->id}");
+ waitFor($page, "@repurpose-item-{$withoutLink->id}");
$page->assertVisible("@repurpose-item-{$withoutLink->id}")
->assertDontSee($withoutLink->source_media_id)
@@ -282,13 +256,13 @@ test('a destination missing its required meta saves anyway but blocks activating
$page = visit(route('app.repurposes.show', $repurpose));
- waitForRepurposeTestId($page, 'activate-repurpose');
+ waitFor($page, '@activate-repurpose');
$page->assertVisible('@activate-repurpose')
->assertMissing('@save-destinations')
->click("@channel-{$tiktok->id}");
- waitForRepurposeTestId($page, 'repurpose-saved');
+ waitFor($page, '@repurpose-saved');
$saved = $repurpose->fresh()->destinations;
@@ -317,11 +291,11 @@ test('an autosave the backend rejects says so instead of failing quietly', funct
$page = visit(route('app.repurposes.show', $repurpose));
- waitForRepurposeTestId($page, "channel-{$tiktok->id}");
+ waitFor($page, "@channel-{$tiktok->id}");
$page->click("@channel-{$tiktok->id}");
- waitForRepurposeTestId($page, 'destinations-error');
+ waitFor($page, '@destinations-error');
$page->assertVisible('@destinations-error')
->assertSee(trans('repurposes.errors.destinations_required'))
@@ -349,7 +323,7 @@ test('the list shows each repurpose as a row that opens it and the back button r
$page = visit(route('app.repurposes.index'));
- waitForRepurposeTestId($page, "repurpose-row-{$repurpose->id}");
+ waitFor($page, "@repurpose-row-{$repurpose->id}");
$page->assertVisible('@create-repurpose-button')
->assertVisible('@header-icon')
@@ -357,12 +331,12 @@ test('the list shows each repurpose as a row that opens it and the back button r
->assertScript('document.documentElement.scrollWidth <= window.innerWidth + 1', true)
->click("@repurpose-row-{$repurpose->id}");
- waitForRepurposeTestId($page, 'repurpose-back');
+ waitFor($page, '@repurpose-back');
$page->assertRoute('app.repurposes.show', ['repurpose' => $repurpose->id])
->click('@repurpose-back');
- waitForRepurposeTestId($page, 'repurposes-table');
+ waitFor($page, '@repurposes-table');
$page->assertRoute('app.repurposes.index')
->resize(390, 844)
@@ -378,14 +352,14 @@ test('without any channel the empty state offers to connect one, like the publis
$this->actingAs($user->fresh());
$page = visit(route('app.repurposes.index'));
- waitForRepurposeTestId($page, 'repurposes-empty');
+ waitFor($page, '@repurposes-empty');
$page->assertVisible('@repurposes-empty-illustration')
->assertSeeIn('@repurposes-empty', __('repurposes.empty.title'))
->assertMissing('@repurposes-empty-create')
->assertSeeIn('@repurposes-empty-connect', __('channels.connect'))
->click('@repurposes-empty-connect');
- waitForRepurposeTestId($page, 'connect-channel-dialog');
+ waitFor($page, '@connect-channel-dialog');
$page->assertVisible('@connect-channel-dialog')
->assertNoJavaScriptErrors();
@@ -396,16 +370,16 @@ test('with a source channel and no repurpose the empty state starts a new one',
$this->actingAs($user);
$page = visit(route('app.repurposes.index'));
- waitForRepurposeTestId($page, 'repurposes-empty');
+ waitFor($page, '@repurposes-empty');
$page->assertVisible('@repurposes-empty-illustration')
->assertMissing('@repurposes-empty-connect')
->click('@repurposes-empty-create');
- waitForRepurposeTestId($page, 'create-repurpose-dialog');
+ waitFor($page, '@create-repurpose-dialog');
$page->assertVisible('@create-repurpose-dialog')
->click('[data-testid="create-repurpose-dialog"] [data-testid="source-account-select"] button');
- waitForRepurposeTestId($page, 'source-account-option');
+ waitFor($page, '@source-account-option');
expect($page->script(<<<'JS'
[...document.querySelectorAll('[data-testid="source-account-option"]')].map((option) => [
@@ -429,7 +403,7 @@ test('the edit page reads like channel settings: source avatar, status, tabs and
$this->actingAs($user);
$page = visit(route('app.repurposes.show', $repurpose))->resize(1440, 1000);
- waitForRepurposeTestId($page, 'repurpose-source-avatar');
+ waitFor($page, '@repurpose-source-avatar');
$page->assertAttribute('@repurpose-source-avatar', 'data-platform', Platform::Instagram->value)
->assertSeeIn('@repurpose-status', __("repurposes.status.{$repurpose->status->value}"))
@@ -441,7 +415,7 @@ test('the edit page reads like channel settings: source avatar, status, tabs and
expect($page->script("document.querySelectorAll('[data-testid=\"repurpose-configuration\"] > hr').length"))->toBe(3);
$page->click('@tab-activity');
- waitForRepurposeTestId($page, 'repurpose-activity-empty');
+ waitFor($page, '@repurpose-activity-empty');
$page->assertAttribute('@tab-activity', 'aria-selected', 'true')
->assertVisible('@repurposes-empty-illustration')
@@ -463,18 +437,18 @@ test('a destination row switch adds and removes the destination', function () {
$this->actingAs($user);
$page = visit(route('app.repurposes.show', $repurpose));
- waitForRepurposeTestId($page, "channel-{$youtube->id}");
+ waitFor($page, "@channel-{$youtube->id}");
$page->assertMissing("@channel-settings-{$youtube->id}")
->click("@channel-{$youtube->id}");
- waitForRepurposeTestId($page, "channel-settings-{$youtube->id}");
- waitForRepurposeTestId($page, 'repurpose-saved');
+ waitFor($page, "@channel-settings-{$youtube->id}");
+ waitFor($page, '@repurpose-saved');
$page->assertAttribute("@channel-{$youtube->id}", 'aria-checked', 'true');
expect(data_get($repurpose->fresh()->destinations, '0.social_account_id'))->toBe($youtube->id);
$page->click("@channel-{$youtube->id}");
- waitForRepurposeCondition($page, "!document.querySelector('[data-testid=\"channel-settings-{$youtube->id}\"]')");
+ waitForGone($page, "@channel-settings-{$youtube->id}");
$page->assertAttribute("@channel-{$youtube->id}", 'aria-checked', 'false')
->assertNoJavaScriptErrors();
@@ -494,24 +468,20 @@ test('the watched format select and the publishing radio save', function () {
$this->actingAs($user);
$page = visit(route('app.repurposes.show', $repurpose));
- waitForRepurposeTestId($page, 'source-format-select');
+ waitFor($page, '@source-format-select');
$page->click('@source-format-select');
- waitForRepurposeTestId($page, 'source-format-option-story');
+ waitFor($page, '@source-format-option-story');
$page->click('@source-format-option-story');
- for ($attempt = 0; $attempt < 50 && $repurpose->fresh()->source_format !== SourceFormat::Story; $attempt++) {
- $page->script('new Promise((resolve) => setTimeout(resolve, 100))');
- }
+ waitForDatabase($page, fn () => $repurpose->fresh()->source_format === SourceFormat::Story);
expect($repurpose->fresh()->source_format)->toBe(SourceFormat::Story);
$page->assertAttribute('@publish-mode-publish', 'aria-checked', 'true')
->click('@publish-mode-draft');
- for ($attempt = 0; $attempt < 50 && $repurpose->fresh()->publish_mode !== PublishMode::Draft; $attempt++) {
- $page->script('new Promise((resolve) => setTimeout(resolve, 100))');
- }
+ waitForDatabase($page, fn () => $repurpose->fresh()->publish_mode === PublishMode::Draft);
expect($repurpose->fresh()->publish_mode)->toBe(PublishMode::Draft);
$page->assertAttribute('@publish-mode-draft', 'aria-checked', 'true')
@@ -529,7 +499,7 @@ test('the list shows each repurpose source and destinations as channel avatars',
$this->actingAs($user);
$page = visit(route('app.repurposes.index'))->resize(1440, 900);
- waitForRepurposeTestId($page, "repurpose-row-{$repurpose->id}");
+ waitFor($page, "@repurpose-row-{$repurpose->id}");
$page->assertSeeIn("@repurpose-row-{$repurpose->id}", $source->display_name)
->assertSeeIn("@repurpose-row-{$repurpose->id}", __('repurposes.formats.reel'));
@@ -556,7 +526,7 @@ test('the destination post types sit centered in their settings panel', function
$this->actingAs($user);
$page = visit(route('app.repurposes.show', $repurpose))->resize(1440, 1000);
- waitForRepurposeTestId($page, "channel-settings-{$facebook->id}");
+ waitFor($page, "@channel-settings-{$facebook->id}");
expect($page->script(<<<JS
(() => {
@@ -614,8 +584,8 @@ test('on a phone the header puts the summary and the actions on their own rows',
$this->actingAs($user);
$page = visit(route('app.repurposes.show', $repurpose))->resize(390, 844);
- waitForRepurposeTestId($page, 'repurpose-summary');
- waitForRepurposeTestId($page, 'repurpose-lifecycle');
+ waitFor($page, '@repurpose-summary');
+ waitFor($page, '@repurpose-lifecycle');
$layout = $page->script(<<<'JS'
(() => {
diff --git a/tests/Browser/SettingsListRowTest.php b/tests/Browser/SettingsListRowTest.php
index 9b9fe7818..f7c3b2792 100644
--- a/tests/Browser/SettingsListRowTest.php
+++ b/tests/Browser/SettingsListRowTest.php
@@ -6,20 +6,6 @@ use App\Models\User;
use App\Models\Webhook;
use App\Models\Workspace;
-function waitForSettingsListRowTestId(mixed $page, string $testId): void
-{
- $page->script(<<<JS
- (async () => {
- const sel = '[data-testid="{$testId}"]';
- for (let i = 0; i < 100; i++) {
- const el = document.querySelector(sel);
- if (el && el.getBoundingClientRect().height > 0) return;
- await new Promise((r) => setTimeout(r, 50));
- }
- })();
- JS);
-}
-
beforeEach(function () {
$this->user = User::factory()->create();
$this->workspace = Workspace::factory()->create([
@@ -39,7 +25,7 @@ test('api key rows render through the shared settings list row', function () {
$row = "[data-testid=\"api-key-row-{$token->id}\"]";
$page = visit(route('app.api-keys.index'));
- waitForSettingsListRowTestId($page, "api-key-row-{$token->id}");
+ waitFor($page, "@api-key-row-{$token->id}");
$page
->assertVisible($row)
@@ -57,7 +43,7 @@ test('webhook rows open the webhook when clicked', function () {
]);
$page = visit(route('app.webhooks.index'));
- waitForSettingsListRowTestId($page, "webhook-row-{$webhook->id}");
+ waitFor($page, "@webhook-row-{$webhook->id}");
$page
->assertSeeIn("@webhook-row-{$webhook->id}", 'example.com/hooks/trypost')
diff --git a/tests/Browser/SettingsSidebarTest.php b/tests/Browser/SettingsSidebarTest.php
index d144f6f32..9bbc96b1d 100644
--- a/tests/Browser/SettingsSidebarTest.php
+++ b/tests/Browser/SettingsSidebarTest.php
@@ -5,35 +5,9 @@ declare(strict_types=1);
use App\Models\User;
use App\Models\Workspace;
-function waitForSettingsSidebarTestId(mixed $page, string $testId): void
-{
- $page->script(<<<JS
- (async () => {
- const sel = '[data-testid="{$testId}"]';
- for (let i = 0; i < 100; i++) {
- const el = document.querySelector(sel);
- if (el && el.getBoundingClientRect().height > 0) return;
- await new Promise((r) => setTimeout(r, 50));
- }
- })();
- JS);
-}
-
-function waitForSettingsSidebarScript(mixed $page, string $condition): void
-{
- $page->script(<<<JS
- (async () => {
- for (let i = 0; i < 100; i++) {
- if ({$condition}) return;
- await new Promise((r) => setTimeout(r, 50));
- }
- })();
- JS);
-}
-
function waitForSettingsSidebarState(mixed $page, string $state): void
{
- waitForSettingsSidebarScript($page, "document.querySelector('[data-slot=\"sidebar\"][data-state]')?.dataset.state === '{$state}'");
+ waitForState($page, '[data-slot="sidebar"][data-state]', "element.dataset.state === '{$state}'");
}
/**
@@ -93,7 +67,7 @@ test('settings pages swap the app sidebar for the settings sidebar', function ()
$this->actingAs(settingsSidebarUser('admin'));
$page = visit(route('app.profile.edit'));
- waitForSettingsSidebarTestId($page, 'settings-sidebar');
+ waitFor($page, '@settings-sidebar');
$page->assertVisible('@settings-sidebar')
->assertVisible('@settings-nav-profile')
@@ -127,7 +101,7 @@ test('members only see the settings they may use', function () {
$this->actingAs(settingsSidebarUser('member'));
$page = visit(route('app.profile.edit'));
- waitForSettingsSidebarTestId($page, 'settings-sidebar');
+ waitFor($page, '@settings-sidebar');
$page->assertVisible('@settings-nav-profile')
->assertVisible('@settings-nav-signatures')
@@ -143,9 +117,9 @@ test('the back link returns to the app', function () {
$this->actingAs(settingsSidebarUser('admin'));
$page = visit(route('app.labels.index'));
- waitForSettingsSidebarTestId($page, 'settings-back');
+ waitFor($page, '@settings-back');
$page->click('@settings-back');
- waitForSettingsSidebarTestId($page, 'sidebar-new');
+ waitFor($page, '@sidebar-new');
$page->assertVisible('@sidebar-new')->assertNoJavaScriptErrors();
});
@@ -154,7 +128,7 @@ test('with the sidebar collapsed the settings nav stays as icons and the footer
$this->actingAs(settingsSidebarUser('admin'));
$page = visit(route('app.profile.edit'))->resize(1280, 900);
- waitForSettingsSidebarTestId($page, 'sidebar-footer-toggle');
+ waitFor($page, '@sidebar-footer-toggle');
$page->click('@sidebar-footer-toggle');
waitForSettingsSidebarState($page, 'collapsed');
$page->script('new Promise((resolve) => setTimeout(resolve, 400))');
@@ -170,7 +144,7 @@ test('with the sidebar collapsed the settings nav stays as icons and the footer
$page->assertMissing('@settings-nav-channels-count');
$page->script('location.reload()');
- waitForSettingsSidebarTestId($page, 'settings-nav-profile');
+ waitFor($page, '@settings-nav-profile');
waitForSettingsSidebarState($page, 'collapsed');
$page->assertVisible('@settings-nav-profile');
diff --git a/tests/Browser/SidebarChannelReorderTest.php b/tests/Browser/SidebarChannelReorderTest.php
index 98becd8a9..63eb73968 100644
--- a/tests/Browser/SidebarChannelReorderTest.php
+++ b/tests/Browser/SidebarChannelReorderTest.php
@@ -7,23 +7,6 @@ use App\Models\User;
use App\Models\Workspace;
use Pest\Browser\Playwright\Client;
-function waitForSidebarReorderCondition(mixed $page, string $condition): void
-{
- $page->script(<<<JS
- (async () => {
- for (let i = 0; i < 100; i++) {
- if ({$condition}) return;
- await new Promise((r) => setTimeout(r, 50));
- }
- })();
- JS);
-}
-
-function waitForSidebarReorderTestId(mixed $page, string $testId): void
-{
- waitForSidebarReorderCondition($page, "(() => { const el = document.querySelector('[data-testid=\"{$testId}\"]'); return el && el.getBoundingClientRect().height > 0; })()");
-}
-
function sidebarReorderMouse(mixed $page, string $method, array $params = []): void
{
$page->script('true');
@@ -129,11 +112,10 @@ function sidebarReorderSettle(mixed $page, User $user, array $expected): void
{
$ids = json_encode($expected);
- for ($attempt = 0; $attempt < 50 && sidebarReorderDbOrder($user) !== $expected; $attempt++) {
- $page->script('new Promise((resolve) => setTimeout(resolve, 100))');
- }
+ waitForDatabase($page, fn (): bool => sidebarReorderDbOrder($user) === $expected);
- waitForSidebarReorderCondition($page, "JSON.stringify([...document.querySelectorAll('[data-testid=\"sidebar-channels-list\"] > [data-testid^=\"sidebar-channel-row-\"]')].map((row) => row.dataset.testid.replace('sidebar-channel-row-', ''))) === JSON.stringify({$ids}) && !document.querySelector('[data-testid=\"sidebar-channel-placeholder\"]')");
+ waitForCondition($page, "JSON.stringify([...document.querySelectorAll('[data-testid=\"sidebar-channels-list\"] > [data-testid^=\"sidebar-channel-row-\"]')].map((row) => row.dataset.testid.replace('sidebar-channel-row-', ''))) === JSON.stringify({$ids})");
+ waitForGone($page, '@sidebar-channel-placeholder');
}
test('the second channel can be dragged to the top twice in a row', function () {
@@ -141,7 +123,7 @@ test('the second channel can be dragged to the top twice in a row', function ()
$this->actingAs($user);
$page = visit(route('app.posts.index'));
- waitForSidebarReorderTestId($page, "sidebar-channel-{$delta->id}");
+ waitFor($page, "@sidebar-channel-{$delta->id}");
sidebarReorderDrag($page, $bravo, $alpha, 0.25);
$expected = [$bravo->id, $alpha->id, $charlie->id, $delta->id];
@@ -165,7 +147,7 @@ test('a placeholder opens where the channel would land and the drop uses it', fu
$this->actingAs($user);
$page = visit(route('app.posts.index'));
- waitForSidebarReorderTestId($page, "sidebar-channel-{$delta->id}");
+ waitFor($page, "@sidebar-channel-{$delta->id}");
$height = $page->script("document.querySelector('[data-testid=\"sidebar-channel-row-{$charlie->id}\"]').offsetHeight");
$page->script(<<<'JS'
@@ -180,7 +162,7 @@ test('a placeholder opens where the channel would land and the drop uses it', fu
JS);
sidebarReorderPickUp($page, $charlie);
- waitForSidebarReorderTestId($page, 'sidebar-channel-placeholder');
+ waitFor($page, '@sidebar-channel-placeholder');
expect($page->script('window.__dragImages'))->toBe(['data:image']);
expect($page->script("document.querySelector('[data-testid=\"sidebar-channel-placeholder-preview\"]')?.textContent"))->toEndWith($charlie->display_name ?: $charlie->username);
@@ -214,7 +196,7 @@ test('escape cancels a drag and restores the order', function () {
$original = [$alpha->id, $bravo->id, $charlie->id, $delta->id];
$page = visit(route('app.posts.index'));
- waitForSidebarReorderTestId($page, "sidebar-channel-{$delta->id}");
+ waitFor($page, "@sidebar-channel-{$delta->id}");
sidebarReorderPickUp($page, $delta);
sidebarReorderMoveTo($page, "sidebar-channel-row-{$alpha->id}", 0.25);
@@ -241,7 +223,7 @@ test('an expanded channel submenu does not shift the drop position', function ()
$this->actingAs($user);
$page = visit(route('app.channels.publish', $alpha));
- waitForSidebarReorderTestId($page, "sidebar-channel-{$alpha->id}-insights");
+ waitFor($page, "@sidebar-channel-{$alpha->id}-insights");
sidebarReorderPickUp($page, $delta);
sidebarReorderMoveTo($page, "sidebar-channel-row-{$alpha->id}", 0.75);
@@ -278,13 +260,13 @@ test('the list scrolls while a channel is dragged near its bottom edge', functio
$this->actingAs($user);
$page = visit(route('app.posts.index'))->resize(1280, 700);
- waitForSidebarReorderTestId($page, "sidebar-channel-{$alpha->id}");
+ waitFor($page, "@sidebar-channel-{$alpha->id}");
expect($page->script("document.querySelector('[data-testid=\"sidebar-channels-list\"]').scrollTop"))->toBe(0);
sidebarReorderPickUp($page, $alpha);
sidebarReorderMoveTo($page, 'sidebar-channels-list', 0.97);
- waitForSidebarReorderCondition($page, '(() => { const list = document.querySelector(\'[data-testid="sidebar-channels-list"]\'); return list.scrollTop + list.clientHeight >= list.scrollHeight - 1; })()');
+ waitForState($page, '@sidebar-channels-list', 'element.scrollTop + element.clientHeight >= element.scrollHeight - 1');
$list = $page->script(<<<'JS'
(() => {
diff --git a/tests/Browser/SidebarChannelsTest.php b/tests/Browser/SidebarChannelsTest.php
index 49b677ac3..29cb65e25 100644
--- a/tests/Browser/SidebarChannelsTest.php
+++ b/tests/Browser/SidebarChannelsTest.php
@@ -7,20 +7,6 @@ use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
-function waitForSidebarChannelsTestId(mixed $page, string $testId): void
-{
- $page->script(<<<JS
- (async () => {
- const sel = '[data-testid="{$testId}"]';
- for (let i = 0; i < 100; i++) {
- const el = document.querySelector(sel);
- if (el && el.getBoundingClientRect().height > 0) return;
- await new Promise((r) => setTimeout(r, 50));
- }
- })();
- JS);
-}
-
function sidebarChannelsUser(string $role): User
{
$owner = User::factory()->create();
@@ -48,7 +34,7 @@ test('admins see channels with settings and connect controls', function () {
$this->actingAs($user);
$page = visit(route('app.posts.index'));
- waitForSidebarChannelsTestId($page, "sidebar-channel-{$channel->id}");
+ waitFor($page, "@sidebar-channel-{$channel->id}");
$page->assertVisible('@sidebar-channels')
->assertVisible('@sidebar-channels-settings')
@@ -64,9 +50,9 @@ test('a channel publish link leads to that channel publish page', function () {
$this->actingAs($user);
$page = visit(route('app.posts.index'));
- waitForSidebarChannelsTestId($page, "sidebar-channel-{$channel->id}");
+ waitFor($page, "@sidebar-channel-{$channel->id}");
$page->click("@sidebar-channel-{$channel->id}");
- waitForSidebarChannelsTestId($page, 'publish-channel-settings');
+ waitFor($page, '@publish-channel-settings');
expect($page->script('window.location.pathname'))->toBe(parse_url(route('app.channels.publish', $channel), PHP_URL_PATH));
$page->assertVisible('@publish-page')
@@ -80,7 +66,7 @@ test('members see channels without admin controls', function () {
$this->actingAs($user);
$page = visit(route('app.posts.index'));
- waitForSidebarChannelsTestId($page, "sidebar-channel-{$channel->id}");
+ waitFor($page, "@sidebar-channel-{$channel->id}");
$page->assertVisible("@sidebar-channel-{$channel->id}")
->assertMissing('@sidebar-channels-settings')
@@ -94,7 +80,7 @@ test('a lost connection is flagged on the channel', function () {
$this->actingAs($user);
$page = visit(route('app.posts.index'));
- waitForSidebarChannelsTestId($page, "sidebar-channel-{$channel->id}-lost");
+ waitFor($page, "@sidebar-channel-{$channel->id}-lost");
$page->assertVisible("@sidebar-channel-{$channel->id}-lost")
->assertMissing("@channel-avatar-disconnected-{$channel->id}")
@@ -107,7 +93,7 @@ test('a lost connection shows one dot on the avatar for members who cannot recon
$this->actingAs($user);
$page = visit(route('app.posts.index'));
- waitForSidebarChannelsTestId($page, "channel-avatar-disconnected-{$channel->id}");
+ waitFor($page, "@channel-avatar-disconnected-{$channel->id}");
$page->assertVisible("@channel-avatar-disconnected-{$channel->id}")
->assertMissing("@sidebar-channel-{$channel->id}-lost")
@@ -118,7 +104,7 @@ test('an empty workspace offers to connect a channel', function () {
$this->actingAs(sidebarChannelsUser('admin'));
$page = visit(route('app.posts.index'));
- waitForSidebarChannelsTestId($page, 'sidebar-channels-empty');
+ waitFor($page, '@sidebar-channels-empty');
$page->assertSeeIn('@sidebar-channels-label', __('sidebar.connect_channels'))
->assertVisible('@sidebar-channels-empty-connect-instagram')
@@ -147,7 +133,7 @@ test('an empty workspace offers to connect a channel', function () {
JS))->toBeTrue();
$page->click('@sidebar-channels-empty');
- waitForSidebarChannelsTestId($page, 'connect-channel-dialog');
+ waitFor($page, '@connect-channel-dialog');
$page->assertVisible('@connect-channel-linkedin')->assertNoJavaScriptErrors();
});
@@ -159,34 +145,22 @@ test('the channel new-post shortcut opens the composer with that channel selecte
$this->actingAs($user);
$page = visit(route('app.posts.index'));
- waitForSidebarChannelsTestId($page, "sidebar-channel-{$channel->id}");
+ waitFor($page, "@sidebar-channel-{$channel->id}");
$page->click("@sidebar-channel-{$channel->id}-new-post");
- waitForSidebarChannelsTestId($page, "composer-account-{$channel->id}");
+ waitFor($page, "@composer-account-{$channel->id}");
$page->assertVisible("@composer-account-{$channel->id}")
->assertMissing("@composer-account-{$other->id}")
->assertNoJavaScriptErrors();
});
-function waitForSidebarChannelsScript(mixed $page, string $condition): void
-{
- $page->script(<<<JS
- (async () => {
- for (let i = 0; i < 100; i++) {
- if ({$condition}) return;
- await new Promise((r) => setTimeout(r, 50));
- }
- })();
- JS);
-}
-
test('the chevron expands and collapses a channel submenu with an animated grid row', function () {
$user = sidebarChannelsUser('admin');
$channel = SocialAccount::factory()->linkedin()->create(['workspace_id' => $user->current_workspace_id]);
$this->actingAs($user);
$page = visit(route('app.posts.index'));
- waitForSidebarChannelsTestId($page, "sidebar-channel-{$channel->id}");
+ waitFor($page, "@sidebar-channel-{$channel->id}");
$submenu = "document.querySelector('[data-testid=\"sidebar-channel-{$channel->id}-submenu\"]')";
@@ -196,13 +170,13 @@ test('the chevron expands and collapses a channel submenu with an animated grid
$page->assertMissing("@sidebar-channel-{$channel->id}-publish")
->click("@sidebar-channel-{$channel->id}-toggle");
- waitForSidebarChannelsScript($page, "{$submenu}.getBoundingClientRect().height > 60");
+ waitForState($page, "@sidebar-channel-{$channel->id}-submenu", 'element.getBoundingClientRect().height > 60');
expect($page->script("document.querySelector('[data-testid=\"sidebar-channel-{$channel->id}-toggle\"]').getAttribute('aria-expanded')"))->toBe('true');
$page->assertVisible("@sidebar-channel-{$channel->id}-publish")
->click("@sidebar-channel-{$channel->id}-toggle");
- waitForSidebarChannelsScript($page, "getComputedStyle({$submenu}).visibility === 'hidden' && {$submenu}.getBoundingClientRect().height === 0");
+ waitForState($page, "@sidebar-channel-{$channel->id}-submenu", "getComputedStyle(element).visibility === 'hidden' && element.getBoundingClientRect().height === 0");
$page->assertMissing("@sidebar-channel-{$channel->id}-publish")
->assertNoJavaScriptErrors();
@@ -216,7 +190,7 @@ test('the sidebar cannot be collapsed', function () {
$this->actingAs($user);
$page = visit(route('app.posts.index'));
- waitForSidebarChannelsTestId($page, 'sidebar-new');
+ waitFor($page, '@sidebar-new');
$sidebar = "document.querySelector('[data-slot=\"sidebar\"]')";
@@ -243,17 +217,17 @@ test('an expanded channel shows its scheduled count on the Publish item', functi
$this->actingAs($user);
$page = visit(route('app.posts.index'));
- waitForSidebarChannelsTestId($page, "sidebar-channel-count-{$channel->id}");
+ waitFor($page, "@sidebar-channel-count-{$channel->id}");
expect(trim((string) $page->script("document.querySelector('[data-testid=\"sidebar-channel-count-{$channel->id}\"]').textContent")))->toBe('3');
$page->click("@sidebar-channel-{$channel->id}-toggle");
- waitForSidebarChannelsTestId($page, "sidebar-channel-{$channel->id}-publish-count");
+ waitFor($page, "@sidebar-channel-{$channel->id}-publish-count");
$page->assertSeeIn('@sidebar-publish-count', '3')
->assertSeeIn("@sidebar-channel-{$channel->id}-publish-count", '3')
->click("@sidebar-channel-{$empty->id}-toggle");
- waitForSidebarChannelsTestId($page, "sidebar-channel-{$empty->id}-publish");
+ waitFor($page, "@sidebar-channel-{$empty->id}-publish");
$page->assertMissing("@sidebar-channel-{$empty->id}-publish-count")
->assertNoJavaScriptErrors();
@@ -265,11 +239,11 @@ test('keyboard focus reveals the channels header actions', function () {
$this->actingAs($user);
$page = visit(route('app.posts.index'));
- waitForSidebarChannelsTestId($page, 'sidebar-channels-label');
+ waitFor($page, '@sidebar-channels-label');
$actions = "document.querySelector('[data-testid=\"sidebar-channels-actions\"]')";
$page->script("document.querySelector('[data-testid=\"sidebar-channels-search\"]').focus()");
- waitForSidebarChannelsScript($page, "getComputedStyle({$actions}).opacity === '1'");
+ waitForState($page, '@sidebar-channels-actions', "getComputedStyle(element).opacity === '1'");
expect($page->script("getComputedStyle({$actions}).opacity"))->toBe('1');
$page->assertMissing('@sidebar-channels-settings')
@@ -317,10 +291,10 @@ test('the channels search button shows its shortcut and opens the command palett
$this->actingAs($user);
$page = visit(route('app.posts.index'));
- waitForSidebarChannelsTestId($page, 'sidebar-channels-label');
+ waitFor($page, '@sidebar-channels-label');
$page->hover('@sidebar-channels-label')->hover('@sidebar-channels-search');
- waitForSidebarChannelsTestId($page, 'sidebar-channels-search-tooltip');
+ waitFor($page, '@sidebar-channels-search-tooltip');
$isMac = (bool) $page->script('/Mac|iPhone|iPad/.test(navigator.platform)');
@@ -347,10 +321,10 @@ test('the channels settings and connect actions show a tooltip above them', func
$this->actingAs($user);
$page = visit(route('app.posts.index'));
- waitForSidebarChannelsTestId($page, 'sidebar-channels-label');
+ waitFor($page, '@sidebar-channels-label');
$page->hover('@sidebar-channels-label')->hover("@sidebar-channels-{$action}");
- waitForSidebarChannelsTestId($page, "sidebar-channels-{$action}-tooltip");
+ waitFor($page, "@sidebar-channels-{$action}-tooltip");
$page->assertSeeIn("@sidebar-channels-{$action}-tooltip", $action === 'settings' ? __('channels.settings') : __('channels.connect'));
@@ -370,7 +344,7 @@ test('only the channel list scrolls while the main nav and the footer stay fixed
$this->actingAs($user);
$page = visit(route('app.posts.index'))->resize(1280, 700);
- waitForSidebarChannelsTestId($page, "sidebar-channel-{$channels->first()->id}");
+ waitFor($page, "@sidebar-channel-{$channels->first()->id}");
$layout = fn (): array => $page->script(<<<'JS'
(() => {
@@ -412,9 +386,9 @@ test('the collapsed sidebar shows every channel network badge without clipping i
$this->actingAs($user);
$page = visit(route('app.channels.publish', $channels->first()->id))->resize(1280, 900);
- waitForSidebarChannelsTestId($page, 'sidebar-footer-toggle');
+ waitFor($page, '@sidebar-footer-toggle');
$page->click('@sidebar-footer-toggle');
- waitForSidebarChannelsScript($page, "document.querySelector('[data-slot=\"sidebar\"][data-state]')?.dataset.state === 'collapsed'");
+ waitForState($page, '[data-slot="sidebar"][data-state]', "element.dataset.state === 'collapsed'");
$page->script('new Promise((resolve) => setTimeout(resolve, 400))');
foreach ($channels as $channel) {
diff --git a/tests/Browser/SidebarLanguageSwitchTest.php b/tests/Browser/SidebarLanguageSwitchTest.php
index 6d7f278ee..98ecc2fd0 100644
--- a/tests/Browser/SidebarLanguageSwitchTest.php
+++ b/tests/Browser/SidebarLanguageSwitchTest.php
@@ -7,20 +7,6 @@ use App\Enums\User\Theme;
use App\Models\User;
use App\Models\Workspace;
-function waitForSidebarLanguageTestId(mixed $page, string $testId): void
-{
- $page->script(<<<JS
- (async () => {
- const sel = '[data-testid="{$testId}"]';
- for (let i = 0; i < 150; i++) {
- const el = document.querySelector(sel);
- if (el && el.getBoundingClientRect().height > 0) return;
- await new Promise((r) => setTimeout(r, 50));
- }
- })();
- JS);
-}
-
test('switching language in the sidebar translates the page in place', function () {
$user = User::factory()->create(['locale' => Locale::English]);
$workspace = Workspace::factory()->create([
@@ -33,7 +19,7 @@ test('switching language in the sidebar translates the page in place', function
$this->actingAs($user);
$page = visit(route('app.calendar'));
- waitForSidebarLanguageTestId($page, 'sidebar-workspace-menu');
+ waitFor($page, '@sidebar-workspace-menu');
// A full page load would clear this, so it doubles as the no-reload assertion.
$page->script('window.__notReloaded = true;');
@@ -55,7 +41,7 @@ test('switching language in the sidebar translates the page in place', function
$japanese = __('sidebar.groups.posts', [], 'ja');
- $page->script("(async () => { for (let i = 0; i < 150; i++) { if (document.body.innerText.includes('{$japanese}')) return; await new Promise((r) => setTimeout(r, 50)); } })();");
+ waitForCondition($page, "document.body.innerText.includes('{$japanese}')");
$page->assertNoJavaScriptErrors();
$page->assertSee($japanese)
@@ -79,7 +65,7 @@ test('the calendar header follows the language, not the previous one', function
$week = now()->startOfMonth()->addDays(10)->startOfWeek();
$page = visit(route('app.calendar', ['view' => 'week', 'week' => $week->toDateString()]));
- waitForSidebarLanguageTestId($page, 'sidebar-workspace-menu');
+ waitFor($page, '@sidebar-workspace-menu');
$page->script(<<<'JS'
(async () => {
@@ -96,7 +82,7 @@ test('the calendar header follows the language, not the previous one', function
})();
JS);
- $page->script('(async () => { for (let i = 0; i < 150; i++) { if (window.__header !== undefined) return; await new Promise((r) => setTimeout(r, 50)); } })();');
+ waitForCondition($page, 'window.__header !== undefined');
// The month name comes from dayjs on the client, so it is the piece that used
// to lag one switch behind the interface strings.
@@ -116,7 +102,7 @@ test('switching theme in the sidebar applies it in place and saves it', function
$this->actingAs($user);
$page = visit(route('app.calendar'));
- waitForSidebarLanguageTestId($page, 'sidebar-workspace-menu');
+ waitFor($page, '@sidebar-workspace-menu');
$page->script('window.__notReloaded = true;');
@@ -140,9 +126,7 @@ test('switching theme in the sidebar applies it in place and saves it', function
expect($page->script('document.documentElement.classList.contains("dark")'))->toBeTrue();
- for ($attempt = 0; $attempt < 30 && $user->refresh()->theme !== Theme::Dark; $attempt++) {
- $page->script('new Promise((r) => setTimeout(r, 100))');
- }
+ waitForDatabase($page, fn () => $user->refresh()->theme === Theme::Dark);
expect($user->theme)->toBe(Theme::Dark);
@@ -150,9 +134,7 @@ test('switching theme in the sidebar applies it in place and saves it', function
expect($page->script('document.documentElement.classList.contains("dark")'))->toBeFalse();
- for ($attempt = 0; $attempt < 30 && $user->refresh()->theme !== Theme::Light; $attempt++) {
- $page->script('new Promise((r) => setTimeout(r, 100))');
- }
+ waitForDatabase($page, fn () => $user->refresh()->theme === Theme::Light);
expect($user->theme)->toBe(Theme::Light);
@@ -173,7 +155,7 @@ test('the user menu has a help and support submenu with the support links', func
$this->actingAs($user);
$page = visit(route('app.calendar'));
- waitForSidebarLanguageTestId($page, 'sidebar-workspace-menu');
+ waitFor($page, '@sidebar-workspace-menu');
$links = $page->script(<<<'JS'
(async () => {
diff --git a/tests/Browser/SidebarMenuTest.php b/tests/Browser/SidebarMenuTest.php
index 258f3a055..fdf63d92f 100644
--- a/tests/Browser/SidebarMenuTest.php
+++ b/tests/Browser/SidebarMenuTest.php
@@ -15,17 +15,7 @@ use App\Models\Workspace;
*/
function waitForSidebarTestId(mixed $page, string $testId): void
{
- $page->script(<<<JS
- (async () => {
- const sel = '[data-testid="{$testId}"]';
- for (let i = 0; i < 100; i++) {
- const el = document.querySelector(sel);
- if (el && el.getBoundingClientRect().height > 0) return;
- await new Promise((r) => setTimeout(r, 50));
- }
- })();
- JS);
-
+ waitFor($page, "@{$testId}");
waitForWebFonts($page);
}
@@ -90,7 +80,7 @@ test('account owners see settings, channels and plans and billing in the sidebar
$page->click('@sidebar-menu-manage-team');
$membersPath = route('app.members', absolute: false);
- $page->script("(async () => { for (let i = 0; i < 150; i++) { if (location.pathname === '{$membersPath}') return; await new Promise((r) => setTimeout(r, 50)); } })();");
+ waitForPath($page, $membersPath);
$page->assertPathIs($membersPath)
->assertNoJavaScriptErrors();
@@ -324,14 +314,7 @@ test('the sidebar menu opens right to left for a right-to-left language', functi
function waitForSidebarState(mixed $page, string $state): void
{
- $page->script(<<<JS
- (async () => {
- for (let i = 0; i < 100; i++) {
- if (document.querySelector('[data-slot="sidebar"][data-state]')?.dataset.state === '{$state}') return;
- await new Promise((r) => setTimeout(r, 50));
- }
- })();
- JS);
+ waitForState($page, '[data-slot="sidebar"][data-state]', "element.dataset.state === '{$state}'");
}
test('the sidebar footer toggle collapses and expands the sidebar and the state survives a reload', function () {
@@ -410,13 +393,7 @@ test('the sidebar auto-collapses below 1024px, can be expanded there, and restor
$page->resize(700, 900);
waitForSidebarTestId($page, 'app-sidebar-trigger');
- $page->script(<<<'JS'
- (async () => {
- for (let i = 0; i < 100 && document.querySelector('[data-testid="sidebar-footer-toggle"]'); i++) {
- await new Promise((r) => setTimeout(r, 50));
- }
- })();
- JS);
+ waitForGone($page, '@sidebar-footer-toggle');
expect($page->script("document.querySelector('[data-testid=\"sidebar-footer-toggle\"]')"))->toBeNull();
$page->resize(1280, 900);
@@ -468,7 +445,7 @@ test('on a phone a global bar with the menu button and logo sits above the conte
$page->click('@app-sidebar-trigger');
$mobileSidebar = '(document.querySelector(\'[data-mobile="true"]\')?.getBoundingClientRect().width ?? 0) > 0';
- $page->script("(async () => { for (let attempt = 0; attempt < 100; attempt++) { if ({$mobileSidebar}) return; await new Promise((resolve) => setTimeout(resolve, 50)); } })()");
+ waitForState($page, '[data-mobile="true"]', 'element.getBoundingClientRect().width > 0');
expect($page->script($mobileSidebar))->toBeTrue();
$page->resize(1280, 900);
diff --git a/tests/Browser/SignaturesPageTest.php b/tests/Browser/SignaturesPageTest.php
index 52eb9f592..df6fca716 100644
--- a/tests/Browser/SignaturesPageTest.php
+++ b/tests/Browser/SignaturesPageTest.php
@@ -6,20 +6,6 @@ use App\Models\User;
use App\Models\Workspace;
use App\Models\WorkspaceSignature;
-function waitForSignaturesPageTestId(mixed $page, string $testId): void
-{
- $page->script(<<<JS
- (async () => {
- const selector = '[data-testid="{$testId}"]';
- for (let attempt = 0; attempt < 200; attempt++) {
- const element = document.querySelector(selector);
- if (element && element.getBoundingClientRect().height > 0) return;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })();
- JS);
-}
-
function signaturesPageOwner(): array
{
$user = User::factory()->create();
@@ -38,7 +24,7 @@ test('the signatures page without signatures shows only the centered illustratio
$this->actingAs($user);
$page = visit(route('app.signatures.index'));
- waitForSignaturesPageTestId($page, 'signatures-empty');
+ waitFor($page, '@signatures-empty');
$page->assertVisible('@signatures-empty-illustration')
->assertMissing('@header-title')
@@ -56,7 +42,7 @@ test('the signatures page without signatures shows only the centered illustratio
JS))->toBeTrue();
$page->click('@signatures-empty-create');
- waitForSignaturesPageTestId($page, 'create-signature-sheet');
+ waitFor($page, '@create-signature-sheet');
$page->assertVisible('@create-signature-sheet')->assertNoJavaScriptErrors();
});
@@ -67,7 +53,7 @@ test('a signature search without results keeps the header and search and shows t
$this->actingAs($user);
$page = visit(route('app.signatures.index', ['search' => 'nothing-matches']));
- waitForSignaturesPageTestId($page, 'empty-state');
+ waitFor($page, '@empty-state');
$page->assertVisible('@header-title')
->assertVisible('@create-signature-button')
@@ -85,7 +71,7 @@ test('clearing a signature search never flashes the no signatures state', functi
$this->actingAs($user);
$page = visit(route('app.signatures.index', ['search' => 'nothing-matches']));
- waitForSignaturesPageTestId($page, 'header-search-input');
+ waitFor($page, '@header-search-input');
$flashed = $page->script(<<<'JS'
(async () => {
@@ -114,7 +100,7 @@ test('the signatures empty state is never cut off on a short screen', function (
$this->actingAs($user);
$page = visit(route('app.signatures.index'));
- waitForSignaturesPageTestId($page, 'signatures-empty');
+ waitFor($page, '@signatures-empty');
$page->resize(375, 480);
expect($page->script(<<<'JS'
diff --git a/tests/Browser/WebhookCreateDialogTest.php b/tests/Browser/WebhookCreateDialogTest.php
index cfbdf1b11..7ec5f1df1 100644
--- a/tests/Browser/WebhookCreateDialogTest.php
+++ b/tests/Browser/WebhookCreateDialogTest.php
@@ -7,35 +7,6 @@ use App\Models\User;
use App\Models\Webhook;
use App\Models\Workspace;
-function waitForWebhookCreateTestId(mixed $page, string $testId): void
-{
- $page->script(<<<JS
- (async () => {
- const sel = '[data-testid="{$testId}"]';
- for (let i = 0; i < 150; i++) {
- const el = document.querySelector(sel);
- if (el && el.getBoundingClientRect().height > 0) return;
- await new Promise((r) => setTimeout(r, 50));
- }
- })();
- JS);
-
- waitForWebFonts($page);
-}
-
-function waitForWebhookCreateTestIdGone(mixed $page, string $testId): void
-{
- $page->script(<<<JS
- (async () => {
- const sel = '[data-testid="{$testId}"]';
- for (let i = 0; i < 150; i++) {
- if (! document.querySelector(sel)) return;
- await new Promise((r) => setTimeout(r, 50));
- }
- })();
- JS);
-}
-
function webhookCreateDialogAdmin(): User
{
$user = User::factory()->create();
@@ -53,9 +24,11 @@ test('creating a webhook happens in a centered dialog with cancel before the pri
$this->actingAs(webhookCreateDialogAdmin());
$page = visit(route('app.webhooks.index'));
- waitForWebhookCreateTestId($page, 'webhooks-empty-create');
+ waitFor($page, '@webhooks-empty-create');
+ waitForWebFonts($page);
$page->click('@webhooks-empty-create');
- waitForWebhookCreateTestId($page, 'create-webhook-dialog');
+ waitFor($page, '@create-webhook-dialog');
+ waitForWebFonts($page);
$page->assertVisible('@create-webhook-endpoint')
->assertVisible('@create-webhook-events-post-created')
@@ -95,7 +68,7 @@ test('creating a webhook happens in a centered dialog with cancel before the pri
->assertSeeIn('@create-webhook-events-count', "0 of {$events} selected")
->click('@create-webhook-events-post-published')
->click('@cancel-create-webhook');
- waitForWebhookCreateTestIdGone($page, 'create-webhook-dialog');
+ waitForGone($page, '@create-webhook-dialog');
$page->assertMissing('@create-webhook-dialog')
->assertNoJavaScriptErrors();
@@ -108,9 +81,11 @@ test('an invalid endpoint shows an inline error and a valid one opens the new we
$this->actingAs($user);
$page = visit(route('app.webhooks.index'));
- waitForWebhookCreateTestId($page, 'webhooks-empty-create');
+ waitFor($page, '@webhooks-empty-create');
+ waitForWebFonts($page);
$page->click('@webhooks-empty-create');
- waitForWebhookCreateTestId($page, 'create-webhook-endpoint');
+ waitFor($page, '@create-webhook-endpoint');
+ waitForWebFonts($page);
$page->fill('@create-webhook-endpoint', 'not-a-url')
->click('@create-webhook-events-post-published')
@@ -123,18 +98,12 @@ test('an invalid endpoint shows an inline error and a valid one opens the new we
$page->fill('@create-webhook-endpoint', 'https://example.com/hooks')
->click('@create-webhook-submit');
- waitForWebhookCreateTestIdGone($page, 'create-webhook-dialog');
+ waitForGone($page, '@create-webhook-dialog');
$webhook = Webhook::query()->where('workspace_id', $user->current_workspace_id)->sole();
$showPath = parse_url(route('app.webhooks.show', $webhook), PHP_URL_PATH);
- $page->script(<<<JS
- (async () => {
- for (let i = 0; i < 100; i++) {
- if (location.pathname === '{$showPath}' && document.body.innerText.includes('example.com/hooks')) return;
- await new Promise((r) => setTimeout(r, 50));
- }
- })();
- JS);
+ waitForPath($page, $showPath);
+ waitForState($page, 'body', "element.innerText.includes('example.com/hooks')");
$page->assertMissing('@create-webhook-dialog')
->assertUrlIs(route('app.webhooks.show', $webhook))
@@ -147,7 +116,8 @@ test('a workspace without webhooks shows only the centered illustration with a c
$this->actingAs(webhookCreateDialogAdmin());
$page = visit(route('app.webhooks.index'));
- waitForWebhookCreateTestId($page, 'webhooks-empty');
+ waitFor($page, '@webhooks-empty');
+ waitForWebFonts($page);
$page->assertVisible('@webhooks-empty-illustration')
->assertSeeIn('@webhooks-empty', __('webhooks.empty_title'))
diff --git a/tests/Browser/WebhookDeleteTest.php b/tests/Browser/WebhookDeleteTest.php
index 5844b2b10..fe6bb4c21 100644
--- a/tests/Browser/WebhookDeleteTest.php
+++ b/tests/Browser/WebhookDeleteTest.php
@@ -6,20 +6,6 @@ use App\Models\User;
use App\Models\Webhook;
use App\Models\Workspace;
-function waitForWebhookDeleteTestId(mixed $page, string $testId): void
-{
- $page->script(<<<JS
- (async () => {
- const sel = '[data-testid="{$testId}"]';
- for (let i = 0; i < 100; i++) {
- const el = document.querySelector(sel);
- if (el && el.getBoundingClientRect().height > 0) return;
- await new Promise((r) => setTimeout(r, 50));
- }
- })();
- JS);
-}
-
test('the webhook list shows the host and status, deletes without typing and opens the details from the menu', function () {
$user = User::factory()->create();
$workspace = Workspace::factory()->create([
@@ -37,7 +23,7 @@ test('the webhook list shows the host and status, deletes without typing and ope
$this->actingAs($user);
$page = visit(route('app.webhooks.index'));
- waitForWebhookDeleteTestId($page, "webhook-row-{$webhook->id}");
+ waitFor($page, "@webhook-row-{$webhook->id}");
$page->assertVisible('@create-webhook-button')
->assertVisible('@header-title')
@@ -54,37 +40,25 @@ test('the webhook list shows the host and status, deletes without typing and ope
$page->assertSeeIn("@webhook-status-{$webhook->id}", __("webhooks.status.{$webhook->status->value}"))
->assertVisible("@webhook-status-dot-{$webhook->id}")
->click("[data-testid=\"webhook-row-{$doomed->id}\"] [data-testid=\"row-actions-trigger\"]");
- waitForWebhookDeleteTestId($page, 'delete-webhook-button');
+ waitFor($page, '@delete-webhook-button');
expect($page->script('location.pathname'))->toBe(route('app.webhooks.index', absolute: false));
$page->click('@delete-webhook-button');
- waitForWebhookDeleteTestId($page, 'confirm-delete-action');
+ waitFor($page, '@confirm-delete-action');
$page->assertMissing('@confirm-delete-input')
->click('@confirm-delete-action');
- $page->script(<<<JS
- (async () => {
- for (let i = 0; i < 100 && document.querySelector('[data-testid="webhook-row-{$doomed->id}"]'); i++) {
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })()
- JS);
+ waitForGone($page, "@webhook-row-{$doomed->id}");
expect(Webhook::query()->whereKey($doomed->id)->exists())->toBeFalse();
$page->click("[data-testid=\"webhook-row-{$webhook->id}\"] [data-testid=\"row-actions-trigger\"]");
- waitForWebhookDeleteTestId($page, "view-webhook-{$webhook->id}");
+ waitFor($page, "@view-webhook-{$webhook->id}");
$page->click("@view-webhook-{$webhook->id}");
- $page->script(<<<'JS'
- (async () => {
- for (let i = 0; i < 60 && !location.pathname.includes('/webhooks/'); i++) {
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })()
- JS);
+ waitForCondition($page, "location.pathname.includes('/webhooks/')");
expect($page->script('location.pathname'))->toBe(route('app.webhooks.show', $webhook, absolute: false));
$page->assertNoJavaScriptErrors();
diff --git a/tests/Browser/WebhookShowTest.php b/tests/Browser/WebhookShowTest.php
index dcb50f949..b9cfd2461 100644
--- a/tests/Browser/WebhookShowTest.php
+++ b/tests/Browser/WebhookShowTest.php
@@ -9,32 +9,6 @@ use App\Models\WebhookLog;
use App\Models\Workspace;
use App\Services\WebhookService;
-function waitForWebhookShowTestId(mixed $page, string $testId): void
-{
- $page->script(<<<JS
- (async () => {
- const sel = '[data-testid="{$testId}"]';
- for (let i = 0; i < 150; i++) {
- const el = document.querySelector(sel);
- if (el && el.getBoundingClientRect().height > 0) return;
- await new Promise((r) => setTimeout(r, 50));
- }
- })();
- JS);
-}
-
-function waitForWebhookShowCondition(mixed $page, string $condition): void
-{
- $page->script(<<<JS
- (async () => {
- for (let i = 0; i < 150; i++) {
- if ({$condition}) return;
- await new Promise((r) => setTimeout(r, 50));
- }
- })();
- JS);
-}
-
/**
* @return array{0: User, 1: Webhook}
*/
@@ -64,7 +38,7 @@ test('the header shows the host, the path and the status', function () {
$this->actingAs($user);
$page = visit(route('app.webhooks.show', $webhook));
- waitForWebhookShowTestId($page, 'webhook-endpoint');
+ waitFor($page, '@webhook-endpoint');
expect($page->script(<<<'JS'
(() => {
@@ -83,7 +57,7 @@ test('the header shows the host, the path and the status', function () {
->assertVisible('@signing-secret')
->click('@webhook-back');
- waitForWebhookShowCondition($page, "location.pathname === '".route('app.webhooks.index', absolute: false)."'");
+ waitForPath($page, route('app.webhooks.index', absolute: false));
expect($page->script('location.pathname'))->toBe(route('app.webhooks.index', absolute: false));
$page->assertNoJavaScriptErrors();
@@ -104,7 +78,7 @@ test('the newest delivery is selected by default and selecting a row shows its p
$this->actingAs($user);
$page = visit(route('app.webhooks.show', $webhook));
- waitForWebhookShowTestId($page, 'webhook-log-detail');
+ waitFor($page, '@webhook-log-detail');
$page->assertSeeIn("@webhook-log-status-{$older->id}", '200')
->assertSeeIn("@webhook-log-status-{$newest->id}", '500')
@@ -118,7 +92,7 @@ test('the newest delivery is selected by default and selecting a row shows its p
->toContain('destructive');
$page->click("@webhook-log-{$older->id}");
- waitForWebhookShowCondition($page, "document.querySelector('[data-testid=\"webhook-log-payload\"]').textContent.includes('older-delivery')");
+ waitForState($page, '@webhook-log-payload', "element.textContent.includes('older-delivery')");
$page->assertSeeIn('@webhook-log-payload', 'older-delivery')
->assertSeeIn('@webhook-log-title', __('webhooks.events.post_published'))
@@ -132,40 +106,40 @@ test('the actions menu pauses, edits and deletes the webhook after a plain confi
$this->actingAs($user);
$page = visit(route('app.webhooks.show', $webhook));
- waitForWebhookShowTestId($page, 'webhook-actions-trigger');
+ waitFor($page, '@webhook-actions-trigger');
$page->click('@webhook-actions-trigger');
- waitForWebhookShowTestId($page, 'toggle-webhook-status');
+ waitFor($page, '@toggle-webhook-status');
$page->assertMissing('@copy-id-button')
->assertVisible('@rotate-secret-menu-item')
->click('@toggle-webhook-status');
$disabled = __('webhooks.status.disabled');
- waitForWebhookShowCondition($page, "document.querySelector('[data-testid=\"webhook-status\"]').textContent.includes('{$disabled}')");
+ waitForState($page, '@webhook-status', "element.textContent.includes('{$disabled}')");
$page->assertSeeIn('@webhook-status', $disabled);
expect($webhook->fresh()->status->value)->toBe('disabled');
- waitForWebhookShowCondition($page, "!document.querySelector('[data-testid=\"toggle-webhook-status\"]')");
+ waitForGone($page, '@toggle-webhook-status');
$page->click('@webhook-actions-trigger');
- waitForWebhookShowTestId($page, 'edit-webhook-button');
+ waitFor($page, '@edit-webhook-button');
$page->click('@edit-webhook-button');
- waitForWebhookShowTestId($page, 'edit-webhook-dialog');
+ waitFor($page, '@edit-webhook-dialog');
$page->assertValue('@edit-webhook-endpoint', 'https://hooks.example.com/trypost/inbound')
->click('@cancel-edit-webhook');
- waitForWebhookShowCondition($page, "!document.querySelector('[data-testid=\"edit-webhook-dialog\"]')");
+ waitForGone($page, '@edit-webhook-dialog');
$page->click('@webhook-actions-trigger');
- waitForWebhookShowTestId($page, 'delete-webhook-button');
+ waitFor($page, '@delete-webhook-button');
$page->click('@delete-webhook-button');
- waitForWebhookShowTestId($page, 'confirm-delete-action');
+ waitFor($page, '@confirm-delete-action');
$page->assertMissing('@confirm-delete-input')
->click('@confirm-delete-action');
$indexPath = route('app.webhooks.index', absolute: false);
- waitForWebhookShowCondition($page, "location.pathname === '{$indexPath}'");
+ waitForPath($page, $indexPath);
expect(Webhook::query()->whereKey($webhook->id)->exists())->toBeFalse()
->and($page->script('location.pathname'))->toBe($indexPath);
@@ -181,14 +155,14 @@ test('send test event pings the endpoint from the header and from the empty deli
$this->actingAs($user);
$page = visit(route('app.webhooks.show', $webhook));
- waitForWebhookShowTestId($page, 'webhook-deliveries-empty');
+ waitFor($page, '@webhook-deliveries-empty');
$page->assertSeeIn('@webhook-deliveries-empty', __('webhooks.deliveries.empty_title'))
->assertSeeIn('@webhook-deliveries-empty', __('webhooks.deliveries.empty_description'))
->assertVisible('@webhooks-empty-illustration')
->assertMissing('@webhook-log-list')
->click('@webhook-deliveries-send-test');
- waitForWebhookShowCondition($page, "document.querySelector('[data-sonner-toast]') !== null");
+ waitForState($page, '[data-sonner-toast]', 'true');
$page->assertSee(__('webhooks.flash.tested'));
@@ -200,7 +174,7 @@ test('send test event pings the endpoint from the header and from the empty deli
JS))->toBe([true, true]);
$page->click('@send-test-webhook');
- waitForWebhookShowCondition($page, "document.querySelectorAll('[data-sonner-toast]').length >= 2");
+ waitForCount($page, '[data-sonner-toast]', 2, '>=');
$page->assertNoJavaScriptErrors();
});
@@ -211,7 +185,7 @@ test('a live delivery update never shows the same delivery twice', function () {
$this->actingAs($user);
$page = visit(route('app.webhooks.show', $webhook));
- waitForWebhookShowTestId($page, 'webhook-actions-trigger');
+ waitFor($page, '@webhook-actions-trigger');
$log = WebhookLog::factory()->create(['webhook_id' => $webhook->id]);
$payload = json_encode([
@@ -233,7 +207,7 @@ test('a live delivery update never shows the same delivery twice', function () {
}
})()
JS);
- waitForWebhookShowCondition($page, "document.querySelectorAll('[data-testid^=\"webhook-log-status-\"]').length >= 3");
+ waitForCount($page, '[data-testid^="webhook-log-status-"]', 3, '>=');
$page->script('new Promise((resolve) => setTimeout(resolve, 800))');
expect($page->script(<<<'JS'
diff --git a/tests/Browser/WelcomeHeaderTest.php b/tests/Browser/WelcomeHeaderTest.php
index 081ed6989..2f34dbf06 100644
--- a/tests/Browser/WelcomeHeaderTest.php
+++ b/tests/Browser/WelcomeHeaderTest.php
@@ -10,48 +10,6 @@ use App\Enums\User\Theme;
use App\Models\User;
use App\Models\Workspace;
-/**
- * Wait for a data-testid element to mount and lay out. Pest browser `@`
- * selectors resolve to data-testid, and assertions do not auto-wait on SPA paint.
- */
-function waitForWelcomeTestId(mixed $page, string $testId): void
-{
- $page->script(<<<JS
- (async () => {
- const sel = '[data-testid="{$testId}"]';
- for (let i = 0; i < 100; i++) {
- const el = document.querySelector(sel);
- if (el && el.getBoundingClientRect().height > 0) return;
- await new Promise((r) => setTimeout(r, 50));
- }
- })();
- JS);
-}
-
-function waitForWelcomeHeaderTextIn(mixed $page, string $testId, string $text): void
-{
- $page->script(<<<JS
- (async () => {
- for (let i = 0; i < 100; i++) {
- if (document.querySelector('[data-testid="{$testId}"]')?.textContent.includes('{$text}')) return;
- await new Promise((r) => setTimeout(r, 50));
- }
- })();
- JS);
-}
-
-function waitForWelcomeHeaderDarkTheme(mixed $page): void
-{
- $page->script(<<<'JS'
- (async () => {
- for (let i = 0; i < 100; i++) {
- if (document.documentElement.classList.contains('dark')) return;
- await new Promise((r) => setTimeout(r, 50));
- }
- })();
- JS);
-}
-
function welcomeHeaderOwner(): User
{
$user = User::factory()->create();
@@ -77,11 +35,11 @@ test('the software step goes back to goals, the step right before it', function
$this->actingAs(welcomeHeaderOwner());
$page = visit(route('app.welcome.software'));
- waitForWelcomeTestId($page, 'welcome-back');
+ waitFor($page, '@welcome-back');
$page->assertVisible('@welcome-step-plan')
->click('@welcome-back');
- waitForWelcomeTestId($page, 'welcome-goals-continue');
+ waitFor($page, '@welcome-goals-continue');
$page->assertRoute('app.welcome.goals')
->assertNoJavaScriptErrors();
@@ -116,10 +74,10 @@ test('the plan step goes back to software, the step right before it', function (
$this->actingAs(welcomeHeaderOwner());
$page = visit(route('app.welcome.plan'));
- waitForWelcomeTestId($page, 'welcome-back');
+ waitFor($page, '@welcome-back');
$page->click('@welcome-back');
- waitForWelcomeTestId($page, 'welcome-software-continue');
+ waitFor($page, '@welcome-software-continue');
$page->assertRoute('app.welcome.software')
->assertNoJavaScriptErrors();
@@ -134,21 +92,21 @@ test('the welcome header switches language through the shared language select an
$this->actingAs($user->fresh());
$page = visit(route('app.welcome.software'));
- waitForWelcomeTestId($page, 'welcome-language-trigger');
+ waitFor($page, '@welcome-language-trigger');
$page->assertVisible('@welcome-back')
->assertVisible('@welcome-step-software')
->click('@welcome-language-trigger');
- waitForWelcomeTestId($page, 'welcome-language-search');
+ waitFor($page, '@welcome-language-search');
$page->fill('@welcome-language-search', 'Português')
->click('@welcome-language-option-pt-BR');
- waitForWelcomeHeaderTextIn($page, 'welcome-language-value', 'Portugu');
+ waitForState($page, '@welcome-language-value', "element.textContent.includes('Portugu')");
expect($user->fresh()->locale)->toBe(Locale::PortugueseBrazil);
$page->click('@theme-toggle');
- waitForWelcomeHeaderDarkTheme($page);
+ waitForState($page, 'html', "element.classList.contains('dark')");
$page->assertNoJavaScriptErrors();
expect($user->fresh()->theme)->toBe(Theme::Dark);
diff --git a/tests/Browser/WelcomeMobileTest.php b/tests/Browser/WelcomeMobileTest.php
index 503ee185d..321a6dbf7 100644
--- a/tests/Browser/WelcomeMobileTest.php
+++ b/tests/Browser/WelcomeMobileTest.php
@@ -9,20 +9,6 @@ use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
-function waitForWelcomeMobileTestId(mixed $page, string $testId): void
-{
- $page->script(<<<JS
- (async () => {
- const selector = '[data-testid="{$testId}"]';
- for (let attempt = 0; attempt < 200; attempt++) {
- const element = document.querySelector(selector);
- if (element && element.getBoundingClientRect().height > 0) return;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })();
- JS);
-}
-
/**
* @param array<string, mixed> $attributes
*/
@@ -119,8 +105,8 @@ test('the welcome header fits a phone and the continue button stays on screen',
$this->actingAs(welcomeMobileOwner($attributes));
$page = visit(route($route))->resize(390, 844);
- waitForWelcomeMobileTestId($page, 'theme-toggle');
- waitForWelcomeMobileTestId($page, $hasBack ? 'welcome-back' : 'welcome-step-persona');
+ waitFor($page, '@theme-toggle');
+ waitFor($page, $hasBack ? '@welcome-back' : '@welcome-step-persona');
$result = welcomeMobileHeaderProblems($page);
diff --git a/tests/Browser/WelcomePlanTest.php b/tests/Browser/WelcomePlanTest.php
index 11c01b7cb..b553ecaf1 100644
--- a/tests/Browser/WelcomePlanTest.php
+++ b/tests/Browser/WelcomePlanTest.php
@@ -10,10 +10,6 @@ use App\Models\User;
use App\Models\Workspace;
use Illuminate\Support\Str;
-/**
- * Wait for a data-testid element to mount and lay out. Pest browser `@`
- * selectors resolve to data-testid, and assertions do not auto-wait on SPA paint.
- */
function welcomePlanVisibleReview(mixed $page): ?string
{
return $page->script(<<<'JS'
diff --git a/tests/Browser/WorkspaceCreateTest.php b/tests/Browser/WorkspaceCreateTest.php
index 58d241fee..7987f147b 100644
--- a/tests/Browser/WorkspaceCreateTest.php
+++ b/tests/Browser/WorkspaceCreateTest.php
@@ -5,20 +5,6 @@ declare(strict_types=1);
use App\Models\User;
use App\Models\Workspace;
-function waitForWorkspaceCreateTestId(mixed $page, string $testId): void
-{
- $page->script(<<<JS
- (async () => {
- const sel = '[data-testid="{$testId}"]';
- for (let i = 0; i < 100; i++) {
- const el = document.querySelector(sel);
- if (el && el.getBoundingClientRect().height > 0) return;
- await new Promise((r) => setTimeout(r, 50));
- }
- })();
- JS);
-}
-
test('a workspace is created from its name alone', function () {
config(['trypost.self_hosted' => true]);
@@ -29,7 +15,7 @@ test('a workspace is created from its name alone', function () {
$this->actingAs($user->fresh());
$page = visit(route('app.workspaces.create'));
- waitForWorkspaceCreateTestId($page, 'workspaces-create-name');
+ waitFor($page, '@workspaces-create-name');
$page->fill('@workspaces-create-name', 'Second')
->click('@workspaces-create-submit')
diff --git a/tests/Browser/WorkspaceInsightsTest.php b/tests/Browser/WorkspaceInsightsTest.php
index 65684ad43..99d5f666c 100644
--- a/tests/Browser/WorkspaceInsightsTest.php
+++ b/tests/Browser/WorkspaceInsightsTest.php
@@ -843,7 +843,7 @@ test('on a phone the custom range applies the two days picked in its sheet', fun
$page->click("[data-testid=\"date-range-picker-sheet\"] [data-slot=\"range-calendar-trigger\"][data-value=\"{$day}\"]");
}
- waitForCondition($page, "new URLSearchParams(location.search).get('end') === '{$days[1]}'");
+ waitForQueryParameter($page, 'end', $days[1]);
$page->assertQueryStringHas('range', 'custom')
->assertQueryStringHas('start', $days[0])
diff --git a/tests/Browser/WritingAssistantTest.php b/tests/Browser/WritingAssistantTest.php
index f6e7c880d..c9a4ea54e 100644
--- a/tests/Browser/WritingAssistantTest.php
+++ b/tests/Browser/WritingAssistantTest.php
@@ -8,45 +8,6 @@ use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
-/**
- * Poll from the page (never sleep()) until the element is laid out and, when
- * given, contains the expected text.
- */
-function waitForWritingAssistantTestId(mixed $page, string $testId, string $text = ''): void
-{
- $expected = json_encode($text);
-
- $page->script(<<<JS
- (async () => {
- for (let attempt = 0; attempt < 300; attempt++) {
- const element = document.querySelector('[data-testid="{$testId}"]');
- if (element?.getBoundingClientRect().height > 0
- && (element.value ?? element.textContent ?? '').includes({$expected})) return;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })();
- JS);
-}
-
-/**
- * The composer opens as an animated dialog; a click that lands before the
- * animation settles is swallowed.
- */
-function waitForWritingAssistantComposer(mixed $page): void
-{
- $page->script(<<<'JS'
- (async () => {
- for (let attempt = 0; attempt < 300; attempt++) {
- const sheet = document.querySelector('[data-testid="post-composer-dialog"]');
- if (sheet?.getAttribute('data-state') === 'open'
- && sheet.getAnimations().every((animation) => animation.playState !== 'running')
- && document.querySelector('[data-testid="composer-add-account"]')?.getBoundingClientRect().height > 0) return;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })();
- JS);
-}
-
/**
* @param array<int, Platform> $platforms
* @return array{0: User, 1: array<int, SocialAccount>}
@@ -79,18 +40,19 @@ function openWritingAssistant(User $user, array $accounts, string $content = '')
test()->actingAs($user);
$page = visit(route('app.posts.create'));
- waitForWritingAssistantComposer($page);
+ waitForOpen($page, '@post-composer-dialog');
+ waitFor($page, '@composer-add-account');
if ($content !== '') {
$page->fill('@composer-base-content', $content);
}
$page->click('@composer-add-account');
foreach ($accounts as $account) {
- waitForWritingAssistantTestId($page, "composer-account-option-{$account->id}");
+ waitFor($page, "@composer-account-option-{$account->id}");
$page->click("@composer-account-option-{$account->id}");
}
- waitForWritingAssistantTestId($page, 'composer-ai-assistant');
+ waitFor($page, '@composer-ai-assistant');
$page->click('@composer-ai-assistant');
- waitForWritingAssistantTestId($page, 'writing-assistant-panel');
+ waitFor($page, '@writing-assistant-panel');
return $page;
}
@@ -118,11 +80,13 @@ test('generate needs four words, regenerates and inserts after the existing text
->assertEnabled('@writing-assistant-generate')
->click('@writing-assistant-generate');
- waitForWritingAssistantTestId($page, 'writing-assistant-suggestion', 'First idea');
+ waitFor($page, '@writing-assistant-suggestion');
+ waitForText($page, '@writing-assistant-suggestion', 'First idea');
$page->assertSeeIn('@writing-assistant-suggestion', 'First idea')
->click('@writing-assistant-regenerate');
- waitForWritingAssistantTestId($page, 'writing-assistant-suggestion', 'Second idea');
+ waitFor($page, '@writing-assistant-suggestion');
+ waitForText($page, '@writing-assistant-suggestion', 'Second idea');
$page->assertSeeIn('@writing-assistant-suggestion', 'Second idea')
->click('@writing-assistant-insert')
->assertValue("@composer-caption-{$accounts[0]->id}", "Existing line\n\nSecond idea")
@@ -136,7 +100,7 @@ test('a rewrite replaces the text and offers no regenerate', function () {
$page = openWritingAssistant($user, $accounts, 'Hello world')
->click('@writing-assistant-mode-rephrase');
- waitForWritingAssistantTestId($page, 'writing-assistant-replace');
+ waitFor($page, '@writing-assistant-replace');
$page->assertMissing('@writing-assistant-regenerate')
->click('@writing-assistant-replace')
->assertValue("@composer-caption-{$accounts[0]->id}", 'Hi everyone')
@@ -169,7 +133,8 @@ test('a premium X channel gets suggestions written for its own limit', function
->fill('@writing-assistant-prompt', 'announce our summer launch today')
->click('@writing-assistant-generate');
- waitForWritingAssistantTestId($page, 'writing-assistant-suggestion', 'Great news');
+ waitFor($page, '@writing-assistant-suggestion');
+ waitForText($page, '@writing-assistant-suggestion', 'Great news');
expect(trim((string) $page->script("document.querySelector('[data-testid=\"writing-assistant-suggestion\"]').textContent")))->toBe($long);
$page->assertNoJavaScriptErrors();
});
@@ -180,24 +145,25 @@ test('switching channel after a suggestion resets the panel and never writes to
test()->actingAs($user);
$page = visit(route('app.posts.create'));
- waitForWritingAssistantComposer($page);
+ waitForOpen($page, '@post-composer-dialog');
+ waitFor($page, '@composer-add-account');
$page->fill('@composer-base-content', 'Hello world')
->click('@composer-add-account');
- waitForWritingAssistantTestId($page, "composer-account-option-{$linkedIn->id}");
+ waitFor($page, "@composer-account-option-{$linkedIn->id}");
$page->click("@composer-account-option-{$linkedIn->id}");
- waitForWritingAssistantTestId($page, "composer-account-option-{$x->id}");
+ waitFor($page, "@composer-account-option-{$x->id}");
$page->click("@composer-account-option-{$x->id}");
- waitForWritingAssistantTestId($page, 'composer-customization');
+ waitFor($page, "@composer-account-{$linkedIn->id}");
$page->click("@composer-account-{$linkedIn->id}")
->click('@composer-ai-assistant');
- waitForWritingAssistantTestId($page, 'writing-assistant-panel');
+ waitFor($page, '@writing-assistant-panel');
$page->click('@writing-assistant-mode-shorten');
- waitForWritingAssistantTestId($page, 'writing-assistant-replace');
+ waitFor($page, '@writing-assistant-replace');
$page->assertSeeIn('@writing-assistant-suggestion', 'Shortened for LinkedIn')
->click("@composer-account-{$x->id}");
- waitForWritingAssistantTestId($page, 'writing-assistant-mode-shorten');
+ waitFor($page, '@writing-assistant-mode-shorten');
$page->assertVisible('@writing-assistant-mode-shorten')
->assertMissing('@writing-assistant-replace')
->assertMissing('@writing-assistant-suggestion')
diff --git a/tests/Browser/XLinkDefusingTest.php b/tests/Browser/XLinkDefusingTest.php
index c663274cf..0db97cb6e 100644
--- a/tests/Browser/XLinkDefusingTest.php
+++ b/tests/Browser/XLinkDefusingTest.php
@@ -48,28 +48,14 @@ function seedXDefusingPost(string $content): array
return [$post, $account];
}
-function waitForXDefusingTestId(mixed $page, string $testId): void
-{
- $page->script(<<<JS
- (async () => {
- for (let attempt = 0; attempt < 100; attempt++) {
- const dialog = document.querySelector('[data-testid="post-composer-dialog"]');
- if (dialog?.getAttribute('data-state') === 'open'
- && dialog.getAnimations().every((animation) => animation.playState !== 'running')
- && document.querySelector('[data-testid="{$testId}"]')?.getBoundingClientRect().height > 0) return;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })();
- JS);
-}
-
test('the x preview shows the link as it will be published', function () {
config()->set('trypost.platforms.x.defuse_links', true);
[$post] = seedXDefusingPost('New post: https://acme.com/blog');
$page = visit(route('app.posts.edit', $post));
- waitForXDefusingTestId($page, 'x-preview-content');
+ waitForOpen($page, '@post-composer-dialog');
+ waitFor($page, '@x-preview-content');
$page->assertSeeIn('@x-preview-content', 'New post: acme(.)com/blog')
->assertDontSeeIn('@x-preview-content', 'https://acme.com/blog')
@@ -82,7 +68,8 @@ test('the x preview leaves the link alone when defusing is disabled', function (
[$post] = seedXDefusingPost('New post: https://acme.com/blog');
$page = visit(route('app.posts.edit', $post));
- waitForXDefusingTestId($page, 'x-preview-content');
+ waitForOpen($page, '@post-composer-dialog');
+ waitFor($page, '@x-preview-content');
$page->assertSeeIn('@x-preview-content', 'New post: https://acme.com/blog')
->assertNoJavaScriptErrors();
diff --git a/tests/Browser/XLongPostComposerTest.php b/tests/Browser/XLongPostComposerTest.php
index 1d8eaf447..cc8efc9ef 100644
--- a/tests/Browser/XLongPostComposerTest.php
+++ b/tests/Browser/XLongPostComposerTest.php
@@ -7,20 +7,6 @@ use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
-function waitForXLongPostTestId(mixed $page, string $testId): void
-{
- $page->script(<<<JS
- (async () => {
- for (let attempt = 0; attempt < 100; attempt++) {
- const sheet = document.querySelector('[data-testid="post-composer-dialog"]');
- if ((sheet === null || sheet.getAnimations().every((animation) => animation.playState !== 'running'))
- && document.querySelector('[data-testid="{$testId}"]')?.getBoundingClientRect().height > 0) return;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- })();
- JS);
-}
-
function xLongPostCounter(mixed $page, string $testId): string
{
return trim((string) $page->script("document.querySelector('[data-testid=\"{$testId}\"]').textContent"));
@@ -46,15 +32,18 @@ test('a premium x card counts against the account limit', function () {
$this->actingAs($user);
$page = visit(route('app.posts.create'));
- waitForXLongPostTestId($page, 'composer-add-account');
+ waitFor($page, '@composer-add-account');
+ waitForState($page, '@post-composer-dialog', "element.getAnimations().every((animation) => animation.playState !== 'running')");
$page->click('@composer-add-account')
->click("@composer-account-option-{$x->id}")
->click("@composer-account-option-{$linkedin->id}");
- waitForXLongPostTestId($page, 'composer-base-content');
+ waitFor($page, '@composer-base-content');
+ waitForState($page, '@post-composer-dialog', "element.getAnimations().every((animation) => animation.playState !== 'running')");
$page->fill('@composer-base-content', 'Hello')
->assertMissing('@composer-base-char-count')
->click('@composer-next');
- waitForXLongPostTestId($page, "composer-char-count-{$x->id}");
+ waitFor($page, "@composer-char-count-{$x->id}");
+ waitForState($page, '@post-composer-dialog', "element.getAnimations().every((animation) => animation.playState !== 'running')");
expect(xLongPostCounter($page, "composer-char-count-{$x->id}"))->toBe('24995');
$page->assertNoJavaScriptErrors();
diff --git a/tests/Browser/YouTubeDescriptionTest.php b/tests/Browser/YouTubeDescriptionTest.php
index 3bc2550d4..81f3a6d2d 100644
--- a/tests/Browser/YouTubeDescriptionTest.php
+++ b/tests/Browser/YouTubeDescriptionTest.php
@@ -46,23 +46,10 @@ function seedYouTubeDescriptionEditor(): array
return [$posts[0], $posts];
}
-function waitForYouTubeElement(mixed $page, string $testId): void
-{
- $page->script(<<<JS
- (async () => {
- for (let i = 0; i < 100; i++) {
- const el = document.querySelector('[data-testid="{$testId}"]');
- if (el && el.getBoundingClientRect().height > 0) return;
- await new Promise(resolve => setTimeout(resolve, 50));
- }
- })();
- JS);
-}
-
test('youtube description editor counts UTF-8 bytes and saves only its independent post', function (int $width, int $height) {
[$post, $posts] = seedYouTubeDescriptionEditor();
$page = visit(route('app.posts.edit', $post))->resize($width, $height);
- waitForYouTubeElement($page, 'youtube-description-0');
+ waitFor($page, '@youtube-description-0');
$page->assertValue('@youtube-description-0', 'Channel 1');
$page->fill('@youtube-description-0', str_repeat('é', 2500))
@@ -93,7 +80,7 @@ test('youtube description editor counts UTF-8 bytes and saves only its independe
test('youtube description clearing restores content fallback without changing another post', function (string $description) {
[$post, $posts] = seedYouTubeDescriptionEditor();
$page = visit(route('app.posts.edit', $post))->resize(375, 812);
- waitForYouTubeElement($page, 'youtube-description-0');
+ waitFor($page, '@youtube-description-0');
$page->fill('@youtube-description-0', $description)
->click('@composer-save-draft')
->assertMissing('@post-composer-dialog');
diff --git a/tests/Pest.php b/tests/Pest.php
index 18039042b..f942b1469 100644
--- a/tests/Pest.php
+++ b/tests/Pest.php
@@ -727,15 +727,18 @@ function waitForWebFonts(mixed $page): void
}
/**
- * Wait until a JavaScript expression is true in the page, for up to 15
- * seconds. Assertions do not wait for the SPA to paint, and a blocking
- * sleep() would starve the server that serves the page, so the page polls.
+ * Wait until a JavaScript expression is true in the page, for up to 30
+ * seconds (longer for a slow import or a fallback that polls the server).
+ * Assertions do not wait for the SPA to paint, and a blocking sleep() would
+ * starve the server that serves the page, so the page polls.
*/
-function waitForCondition(mixed $page, string $condition): void
+function waitForCondition(mixed $page, string $condition, int $seconds = 30): void
{
+ $attempts = $seconds * 20;
+
$page->script(<<<JS
(async () => {
- for (let i = 0; i < 300; i++) {
+ for (let i = 0; i < {$attempts}; i++) {
if ({$condition}) return;
await new Promise((resolve) => setTimeout(resolve, 50));
}
@@ -779,29 +782,41 @@ function jsSelector(string $selector): string
* Wait until an element matching the selector exists and the expression,
* written about `element`, is true: "element.getAttribute('aria-checked') === 'true'".
*/
-function waitForState(mixed $page, string $selector, string $expression): void
+function waitForState(mixed $page, string $selector, string $expression, int $seconds = 30): void
{
$selector = jsSelector($selector);
- waitForCondition($page, "((element) => element && ({$expression}))(document.querySelector({$selector}))");
+ waitForCondition($page, "((element) => element && ({$expression}))(document.querySelector({$selector}))", $seconds);
}
/**
* Wait until an element matching the selector is mounted and laid out.
*/
-function waitFor(mixed $page, string $selector): void
+function waitFor(mixed $page, string $selector, int $seconds = 30): void
{
- waitForState($page, $selector, 'element.getBoundingClientRect().height > 0');
+ waitForState($page, $selector, 'element.getBoundingClientRect().height > 0', $seconds);
+}
+
+/**
+ * Wait until the element matching the selector is open (its `data-state`,
+ * `open` by default) and has finished animating in, so a click or a
+ * measurement lands where the user would see it.
+ */
+function waitForOpen(mixed $page, string $selector, string $state = 'open'): void
+{
+ $state = json_encode($state);
+
+ waitForState($page, $selector, "element.getAttribute('data-state') === {$state} && element.getAnimations().every((animation) => animation.playState !== 'running')");
}
/**
* Wait until no element matches the selector.
*/
-function waitForGone(mixed $page, string $selector): void
+function waitForGone(mixed $page, string $selector, int $seconds = 30): void
{
$selector = jsSelector($selector);
- waitForCondition($page, "!document.querySelector({$selector})");
+ waitForCondition($page, "!document.querySelector({$selector})", $seconds);
}
/**
@@ -815,6 +830,17 @@ function waitForText(mixed $page, string $selector, string $text): void
waitForCondition($page, "[...document.querySelectorAll({$selector})].some((element) => element.textContent.includes({$text}))");
}
+/**
+ * Wait until the number of elements matching the selector compares to the
+ * count: exactly (`===`, the default) or with another operator (`>=`, `>`).
+ */
+function waitForCount(mixed $page, string $selector, int $count, string $operator = '==='): void
+{
+ $selector = jsSelector($selector);
+
+ waitForCondition($page, "document.querySelectorAll({$selector}).length {$operator} {$count}");
+}
+
/**
* Wait until one element is gone or another is shown, whichever happens
* first, so the assertion after it fails at once on the other outcome