Laravel Waitlist:測試整合
當撰寫或修正使用 taldres/laravel-waitlist 的應用程式測試時,使用此技能:測試其表單、監聽器、郵件和頁面,而非套件本身。
主要目標
- 透過套件的公開 API,使用真實令牌和真實狀態變更,測試應用程式在等待清單周圍的自有程式碼
工作流程
1. 設定
- 套件的遷移檔已發佈至
database/migrations,因此RefreshDatabase會建立資料表。 - 必須在測試環境中設定
APP_KEY:地址會以它衍生的金鑰進行加密和查詢。 - 事件實作
ShouldDispatchAfterCommit;搭配RefreshDatabase時,它們仍會照常派遣。 - 套件路由在啟動時註冊。若要測試它們,請在
phpunit.xml或.env.testing中設定WAITLIST_ROUTES_ENABLED=true;在測試內部使用config()->set()為時已晚。空的WAITLIST_ROUTES_ENABLED=是組態錯誤;關閉的路由會回應404。 - 應用程式的
WaitlistServiceProvider在測試中啟動,因此其清單、欄位和頁面都會存在。測試內部的Waitlist::define()會僅為該測試取代該專案;下一個測試會再次啟動應用程式並使用提供者的定義。 - 請使用列舉(而非字串)的鍵來設定其他套件組態:
config()->set(ConfigKey::DoubleOptIn->value, false)(Taldres\Waitlist\Enums\ConfigKey;預設值位於套件的config/waitlist.php)。 - 設定錯誤會拋出
InvalidConfigurationException,絕不會是WaitlistException;請斷言它,不要在應用程式程式碼中捕獲它。無法讀取的組態值也是如此,命名鍵:null表示從不或關閉,而代表「永遠」的數字會被拒絕(連結不得在 2038-01-19 之後結束,保留期間不得回溯至 1970 年之前)。
2. 回傳表單顯示的內容
措辭可以是單一文字或每個地區設定一個;請回傳服務時所使用的版本和地區設定:
use Taldres\Waitlist\Facades\Waitlist;
use Taldres\Waitlist\Support\PurposeWording;
$purposes = collect(Waitlist::purposes('beta'))
->filter(fn (PurposeWording $wording) => $wording->required) // 根據測試需求加入選用項目
->mapWithKeys(fn (PurposeWording $wording) => [$wording->purpose => ['version' => $wording->version, 'locale' => $wording->locale]])
->all();
$result = Waitlist::for('beta')->add('[email protected]', $purposes);
3. 取得純文字令牌
純文字確認令牌僅存在於 EntrySubscribed 的負載中,且僅在啟用雙重選擇加入的清單上。取消訂閱和管理令牌也來自 Waitlist::unsubscribeToken($entry)->token 和 Waitlist::manageLink($entry)->token。
use Illuminate\Support\Facades\Event;
use Taldres\Waitlist\Enums\EntryStatus;
use Taldres\Waitlist\Events\EntrySubscribed;
Event::fake([EntrySubscribed::class]);
Waitlist::for('beta')->add('[email protected]', $purposes);
$event = Event::dispatched(EntrySubscribed::class)->first()[0];
$entry = Waitlist::confirm($event->confirmToken);
expect($entry->status)->toBe(EntryStatus::Confirmed); // 或 $this->assertSame(...)
若要讓真實的監聽器繼續執行(例如郵件監聽器)並同時捕獲令牌,請改用 listen 而非 fake:
$token = null;
Event::listen(function (EntrySubscribed $event) use (&$token) {
$token = $event->confirmToken;
});
$event->unsubscribeToken 在取消訂閱測試中作用相同,ManageLinkRequested::$manageToken 則用於偏好設定頁面。
在設定了 ->doubleOptIn(false)(或關閉了 waitlist.double_opt_in.enabled)的清單上,EntrySubscribed 會以 requiresConfirmation 為 false 且 confirmToken 為 null 觸發,然後觸發 EntryConfirmed;該項目已確認。被 max_pending_per_address 阻止的註冊則完全不會觸發 EntrySubscribed($result->outcome 為 confirmation_deferred)。
4. 斷言郵件
use Illuminate\Support\Facades\Mail;
Mail::fake();
Waitlist::for('beta')->add('[email protected]', $purposes);
Mail::assertSent(ConfirmWaitlistMail::class, fn ($mail) => $mail->hasTo('[email protected]'));
佇列監聽器會在使用 QUEUE_CONNECTION=sync(Laravel 的測試預設值)時內聯執行。
5. HTTP 路由
use Illuminate\Routing\Middleware\ThrottleRequests;
$this->withoutMiddleware(ThrottleRequests::class); // 來自同一個測試 IP 的大量註冊
Event::fake([EntrySubscribed::class]);
$wording = $this->getJson('/waitlist/purposes?list=beta')->assertOk()->json('data.0');
$this->postJson('/waitlist', [
'email' => '[email protected]',
'list' => 'beta',
'purposes' => [$wording['purpose'] => ['version' => $wording['version'], 'locale' => $wording['locale']]],
])->assertStatus(202);
$token = Event::dispatched(EntrySubscribed::class)->first()[0]->confirmToken;
$this->postJson("/waitlist/confirm/{$token}")->assertOk()->assertJsonPath('data.status', 'confirmed');
$this->getJson('/waitlist/confirm/unknown')->assertNotFound()->assertJsonPath('error', 'invalid_token');
套件自身的拒絕會命名一個 error(invalid_token、expired_token、unknown_list、not_subscribed、list_unavailable)。請斷言它:沒有 error 的 404 是錯誤的 URL、已關閉的路由或 useWaitlist 閘道,並且對於未知令牌會通過 assertNotFound()。
只有 HTTP 註冊會套用專案的欄位;add() 信任其呼叫者。在測試中定義它們以斷言 422:
use Taldres\Waitlist\Definitions\ProjectDefinition;
Waitlist::define(function (ProjectDefinition $project): void {
$project->purpose('waitlist', ['v1' => 'Email me.']);
$project->list('teams', purpose: 'waitlist')->fields(['contact_phone' => ['required']]);
});
$this->postJson('/waitlist', [/* email, list, purposes */])->assertJsonValidationErrors('metadata.contact_phone');
請使用 postJson()/getJson():若沒有 Accept: application/json,專案 urls() 中的頁面會將回應變成重新導向。
6. 機器人檢查與清除
use Taldres\Waitlist\Events\EntryForgotten;
Waitlist::verifySpamUsing(fn () => true); // 在測試中繞過 Turnstile 等
Waitlist::verifySpamUsing(fn () => false); // 斷言 422 "Spam check failed."
Waitlist::verifySpamUsing(null); // 恢復為已設定的保護器
Event::fake([EntryForgotten::class]);
Waitlist::allProjects()->forget('[email protected]');
Event::assertDispatched(EntryForgotten::class, fn (EntryForgotten $event) => $event->email === '[email protected]');
規則、參考與範本
- 透過公開 API 斷言狀態:
$entry->status、hasConsentFor()、Waitlist::for($list)->snapshot()、recipients()->count()。 - 註冊結果:
$result->outcome(SubscribeOutcome:started、confirmation_resent、resend_suppressed、already_confirmed、resubscribed、confirmation_deferred)。 - 透過 HTTP,註冊對新地址和已知地址都回應
202;請斷言狀態,而非回應主體。
範例
- 「測試註冊是否會發送確認郵件」:步驟 2 和 4。
- 「測試確認頁面」:步驟 3 和 5,或使用捕獲的令牌呼叫控制器路由。
- 「測試電子報僅發送給同意的人」:註冊兩個地址,其中一個具有選擇性的目的,確認兩者,斷言
Waitlist::recipients('newsletter')->count() === 1。
反模式
- 使用工廠或
create()建立WaitlistEntry、訂閱或同意;應使用add()和令牌方法,否則會跳過事件和不變量。 - 從資料庫欄位讀取令牌;應使用事件或
Waitlist::unsubscribeToken()與Waitlist::manageLink()。 - 在測試內部使用
config()->set()啟用路由。 - 在斷言確認郵件的測試中 fake
EntrySubscribed。 - 使用箭頭函數來捕獲令牌:它們是按值捕獲。