skeith22's avatar
Level 22

How to assert Http::fake response if it doesn't return a TestResponse class

Does anyone how to test an Http:fake response, since you can't use $this->assertStatus(), cause it doesn't return a TestResponse class.

like you're able to assertStatus, assertJson, and etc

Http::preventStrayRequests();

Http::fake([
    '*' => Http::response(['name' => 'John Doe'], 200)
]);

return Http::post('http:://your-domain.test');

returned values from this code, is not an Illuminate\Testing\TestResponse class, but a GuzzleHttp\Psr7\Response class

0 likes
1 reply
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

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:

  1. Set up the fake response:

    Http::preventStrayRequests();
    
    Http::fake([
        '*' => Http::response(['name' => 'John Doe'], 200)
    ]);
    
  2. Send the request:

    $response = Http::post('http://your-domain.test');
    
  3. Assert the response: Since the response is a GuzzleHttp\Psr7\Response object, 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());
    
  4. Using assertSent to verify the request: You can also use assertSent to 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.

1 like

Please or to participate in this conversation.