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(...)
为了保持真实监听器运行(例如邮件监听器)并仍然捕获令牌,请使用监听而非伪造:
$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' => '请给我发邮件。']);
$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 “垃圾检查失败。”
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()启用路由。 - 在断言确认邮件的测试中伪造
EntrySubscribed。 - 使用箭头函数捕获令牌:它们按值捕获。