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

[11.x] Add assertJsonFragments assertion #54576

Merged
merged 1 commit into from
Feb 12, 2025

Conversation

lioneaglesolutions
Copy link
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
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
46 checks passed
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.

None yet

3 participants