To test an Http::fake response in Laravel, you can use the assertSent method provided by the Http facade to assert that a request was sent and to inspect the response. Since the response is a GuzzleHttp\Psr7\Response object, you can directly assert its status and content.
Here's how you can do it:
-
Set up the fake response:
Http::preventStrayRequests(); Http::fake([ '*' => Http::response(['name' => 'John Doe'], 200) ]); -
Send the request:
$response = Http::post('http://your-domain.test'); -
Assert the response: Since the response is a
GuzzleHttp\Psr7\Responseobject, you can use its methods to assert the status and content. For example:$this->assertEquals(200, $response->status()); $this->assertEquals(['name' => 'John Doe'], $response->json()); -
Using
assertSentto verify the request: You can also useassertSentto ensure that the request was made and to inspect the request and response:Http::assertSent(function ($request) { return $request->url() === 'http://your-domain.test' && $request['name'] === 'John Doe'; });
Here is the complete example:
use Illuminate\Support\Facades\Http;
Http::preventStrayRequests();
Http::fake([
'*' => Http::response(['name' => 'John Doe'], 200)
]);
$response = Http::post('http://your-domain.test');
// Assert the response status
$this->assertEquals(200, $response->status());
// Assert the response content
$this->assertEquals(['name' => 'John Doe'], $response->json());
// Assert that the request was sent
Http::assertSent(function ($request) {
return $request->url() === 'http://your-domain.test' &&
$request['name'] === 'John Doe';
});
This way, you can effectively test the Http::fake response and ensure that your application behaves as expected.