How to mock the Twilio library in Laravel

  Kiến thức lập trình

I am using the Twilio library for php/laravel to send sms message. I would like to know could I mock it in my tests, I just want to make sure the create method is call and return a correct message

SmsController.php

$twilio = new Client(‘xxxxxxxxx’, ‘xxxxxxxxxxxxxxxxx’);

$message = $twilio->messages->create(
    "whatsapp:+" . $request->input('user_phone'),
    [
        "mediaUrl" => [
            $request->input('url'),
        ],
        "from" => "whatsapp:+xxxxxxxxx",
    ]
);

return response(['message_sid' => $message->sid]);

This is the test:

use TwilioRestClient;
  ....
  ....

    Http::fake();
    
        $mock = $this->partialMock(Client::class, function (MockInterface $mock) {
            $mock->shouldReceive('create')
                ->with(
                    "whatsapp:+xxxxxxxx",
                    [
                        "mediaUrl" => [
                            "https://url.com/image.jpg",
                        ],
                        "from" => "whatsapp:+xxxxxxxxx",
                    ]
                );
        });
    
        $this->postJson('/twilio/user-message')
            ->assertOk();

But I am getting this error:
[HTTP 401] Unable to create record: Authentication Error – invalid username

Maybe is because it is supposed to pass in the credentiales in the constructor, but even if I do that, I should not make http request in tests.
What can I do?

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website

LEAVE A COMMENT