Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unit Testing #1118

Open
khalidmaquilang opened this issue Mar 7, 2024 · 1 comment
Open

Unit Testing #1118

khalidmaquilang opened this issue Mar 7, 2024 · 1 comment

Comments

@khalidmaquilang
Copy link

khalidmaquilang commented Mar 7, 2024

Please guide me on how to write test for this in laravel

@Mnikoei
Copy link

Mnikoei commented Jan 26, 2025

Please guide me on how to write test for this in laravel

You can set a fake HTTP handler in the setUp method of your base test case class:

protected function setUp(): void
{
    parent::setUp();
    \Telegram\Bot\Laravel\Facades\Telegram::setHttpClientHandler(
        (new FakeHttpHandler())->url('https://fake.telegram.org')
    );
}

And your fake HTTP handler can be like this:

use GuzzleHttp\Promise\PromiseInterface;
use Illuminate\Support\Facades\Http;
use Psr\Http\Message\ResponseInterface;
use Telegram\Bot\HttpClients\GuzzleHttpClient;

class FakeHttpHandler extends GuzzleHttpClient
{
    protected string $url = 'url';

    public function send(
        string $url,
        string $method,
        array $headers = [],
        array $options = [],
        bool $isAsyncRequest = false
    ): ResponseInterface|PromiseInterface|null {

        $response = Http::post($this->url, []);

        return $response->toPsrResponse();
    }

    public function url(string $url): static
    {
        $this->url = $url;

        return $this;
    }
}

Then you can simply write tests and assert requested data to the Telegram server by Http::fake():

public function testSample()
{
    Http::fake();

    // your actions that send request to Telegram server

    Http::assertSent(function (Request $request) {
        // $request->url() === 'https://fake.telegram.org',
        // $request->body() === expected data to be sent to telegram server
    });
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants