3

I have a Laravel 8 app I am writing a test for. Here is what my data looks like:

{
    "data": [
        {
            "name": "Cumque ex quos.",
            "createdAt": "2020-12-29T17:15:32.000000Z",
            "updatedAt": "2020-12-29T17:15:32.000000Z",
            "startAt": "2021-01-18 17:15:32",
            "endAt": "2021-01-18 17:15:32",
            "startedAt": null,
            "status": "Running",
            "range": {
                "type": "percentage",
                "max": 0,
                "min": 0
            },
        },
        {
            "name": "Cumque ex quos 2.",
            "createdAt": "2020-12-29T17:15:32.000000Z",
            "updatedAt": "2020-12-29T17:15:32.000000Z",
            "startAt": "2021-01-18 17:15:32",
            "endAt": "2021-01-18 17:15:32",
            "startedAt": null,
            "status": "Running",
            "range": {
                "type": "percentage",
                "max": 20,
                "min": 100
            },
        },
    ],
    "other_keys" [ ... ];
}

I want to test that every value of status in the response is equal to the value Running. Here's what my test looks like:

/** @test */
public function should_only_return_data_that_are_running()
{
    $response = $this->getJson('/api/v2/data');

    $response->assertJsonPath('data.*.status', 'Running');
}

This fails with the following:

Failed asserting that Array &0 (
    0 => 'Running'
    1 => 'Running'
) is identical to 'Running'.

I am obviously testing this incorrectly. What's the best way to test all of the objects returned in the data array and ensure that the status value is equal to Running?

1 Answer 1

1

Because you're asserting a path that includes a wildcard, you will be getting the value of each matching item (this function uses the data_get() helper in the background.) You'll need to build a structure with the same number of elements. Something like this maybe:

public function should_only_return_data_that_are_running()
{
    $response = $this->getJson('/api/v2/data');
    $test = array_fill(0, count($response->data), 'Running');
    $response->assertJsonPath('data.*.status', $test);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.