I'm using Laravel 10 and Pest. A test that involves MailerSend client is giving me this error. I'm using the Mailsender PHP SDK:
Error: Typed property MailerSend\MailerSend::$bulkEmail must not be accessed before initialization in /opt/project/app/Actions/Email/SendEmail.php:33
This is the test:
it('sends an email', function () {
Config::set('services.mailersend.key', 'foo');
$this->mock(MailerSend::class, function (MockInterface $mock) {
$mock->shouldReceive('bulkEmail->send')
->once()
->andReturn([
'response' => 'success',
'data' => [
'status_code' => 202,
],
'body' => [
'bulk_email_id' => '123foo'
]
]);
});
actingAsAdmin();
postJson(route($this->route, $this->payload))
->assertOk();
});
I've implemented the client in the boot of AppServiceProvider:
$this->app->bind(MailerSend::class, function () {
return (new MailerSend([
'api_key' => Config::get('services.mailersend.key')
]));
});
And I'm using it in an action, injecting it:
class SendEmail
{
public function __construct(private readonly MailerSend $mailerSendClient)
{
//
}
/**
* Send an email.
*/
public function run(SendEmailDto $sendEmailDto): array
{
$bulkEmailParams = [];
foreach($sendEmailDto->recipients as $recipient) {
$bulkEmailParams[] = (new EmailParams())
->setFrom('[email protected]')
->setFromName('My Website')
->setRecipients($recipient)
->setSubject($sendEmailDto->subject)
->setHtml($sendEmailDto->text);
}
return $this->mailerSendClient
->bulkEmail
->send($bulkEmailParams);
}
}
The endpoint works well, the emails are delivered, but the test won't pass.