3

Faking HTTP requests in Laravel

 2 years ago
source link: https://freek.dev/2099-faking-http-requests-in-laravel
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Oh Dear is the all-in-one monitoring tool for your entire website. We monitor uptime, SSL certificates, broken links, scheduled tasks and more. You'll get a notifications for us when something's wrong. All that paired with a developer friendly API and kick-ass documentation. O, and you'll also be able to create a public status page under a minute. Start monitoring using our free trial now.

Faking HTTP requests in Laravel

Original – Oct 25th 2021 by Brent Roose – 2 minute read

Have you ever had to write an API integration from scratch? Where you're managing the HTTP calls yourself instead of being able to rely on third-party packages?

You might have used Guzzle to do so or, maybe better, Laravel's HTTP client.

If you're using the latter one, you'll be happy to know that the HTTP facade offers some great testing tools.

Imagine a repository class that can fetch RSS feeds from the web and parse them into a collection of structured data. Maybe something like this:

class RssRepository
{
    public function fetch(string $url)
    {
        $rss = Http::get($url)->body();

        return Rss::parse($rss)->map(
            fn (array $data)
                => RssEntry::fromArray($data)
        );
    }
}

Now, you definitely want to test whether your mapping logic works, but you don't want to send a real HTTP request every time you run your test. That's where the HTTP fake can help you:

Http::fake([
    'https://test.com/*'
        => Http::response($fakeRssBody),
]);

Notice the * wildcard in the URL? That's right! The HTTP fake is able to return different responses based on the URL and even supports wildcards! You could even choose to use one wildcard for all requests:

Http::fake([
    '*' => Http::response($fakeRssBody),
]);

There is a little more to tell about HTTP fakes, sequences for example; but we'll cover that in our Testing Laravel course.

Stay up to date with all things Laravel, PHP, and JavaScript.

Follow me on Twitter. I regularly tweet out programming tips, and what I myself have learned in ongoing projects.

Every two weeks I send out a newsletter containing lots of interesting stuff for the modern PHP developer.

Expect quick tips & tricks, interesting tutorials, opinions and packages. Because I work with Laravel every day there is an emphasis on that framework.

Rest assured that I will only use your email address to send you the newsletter and will not use it for any other purposes.

Comments #


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK