Skip to content

[11.x] Add assertJsonFragments assertion#54576

Merged
taylorotwell merged 1 commit into
laravel:11.xfrom
lioneaglesolutions:json-fragments
Feb 12, 2025
Merged

[11.x] Add assertJsonFragments assertion#54576
taylorotwell merged 1 commit into
laravel:11.xfrom
lioneaglesolutions:json-fragments

Conversation

@lioneaglesolutions
Copy link
Copy Markdown
Contributor

Problem

Sometimes when asserting a JSON response, it can be helpful when you're looking for multiple fragments at once. A concrete example is when you want to assert some meta values regarding pagination.

The current test looks like this;

it('can paginate teams', function () {
    $user = User::factory()->create();

    $teams = Team::factory()->count(26)->create();

    actingAs($user)
        ->getJson('v2/teams?page[size]=25&page[number]=2')
        ->assertSuccessful()
        ->assertJsonStructure([
            // ...
        ])->assertJsonFragment([
            'current_page' => 2,
        ])->assertJsonFragment([
            'per_page' => 25,
        ])->assertJsonFragment([
            'total' => 26,
        ]);
});

Now the meta key in the response will contain all of the pagination data but it's hard to prepare an assertion for that entire part of the response. Particularly, often you only want to assert a handful of the key/value pairs of the response.

Solution

By adding the assertJsonFragments method, it means you don't have to chain the assertJsonFragment calls;

it('can paginate teams', function () {
    $user = User::factory()->create();

    $teams = Team::factory()->count(26)->create();

    actingAs($user)
        ->getJson('v2/teams?page[size]=25&page[number]=2')
        ->assertSuccessful()
        ->assertJsonStructure([
            // ...
        ])->assertJsonFragments([
            ['current_page' => 2],
            ['per_page' => 25],
            ['total' => 26]
        ]);
});

* @param array $data
* @return $this
*/
public function assertJsonFragments(array $data)
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just a quick thought: might be nice if this were variadic so a user could write:

$response->assertJsonFragments(
    ['current_page' => 2],
    ['per_page' => 25],
    ['total' => 26]
);

@taylorotwell taylorotwell merged commit 241bab4 into laravel:11.x Feb 12, 2025
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

Successfully merging this pull request may close these issues.

3 participants