spatie/phpunit-snapshot-assertions

Allow passing variables to Snapshot to enable dynamic responses

Closed this issue · 1 comments

Hi there,

first of all thanks for the package, it's more like a standard for me to install when using controller level tests etc. Thanks!

There's one thing that I mostly run into and had different strategies to get around: dynamic values

Let's assume if test the json response of a POST endpoint for creating a resource and unfortunately I'm unable to use uuid generated on client side but auto increment (i know 🙈)

POST /api/book

Response:

{
     "id": "123456",
     "title": "Some Title",
     "author": "Jane Doe",
     "ISBN": "978-0-545-01022-1",
     "cover": "https://bucket.foo/bar/9128124.webp",
     "published": 2017,
     "createdAt": "2024-03-08T17:37:09+00:00"
     "more": "values"
}

And id and createdAt change every time. Yes, there are different strategies possible (e.g. mocking on api side, custom driver, stripping those parts ...), but I wanted to propose a built-in solution to support this out of the box:

#[DataProvider('provideExampleRequests')]
public function testCreateBookEndpoint(string $requestBody): void
{
    $response = $this->client->('POST', $requestBody);

    // explicit template method
    $this->assertMatchesJsonPathSnapshot($response, [
         '$.id' => '@\d@',
         '$.createdAt' => '@([\d:\-\+])@',
    ];
}

With the key being a json path and the key a regex.

Honestly, not so sure if that's easy, but wanted to get your opinion and check if i'm missing an obvious solution here.

WDYT?

PS: OC I'd be up to work on the solution if you consider this feature valuable.

Dear contributor,

because this issue seems to be inactive for quite some time now, I've automatically closed it. If you feel this issue deserves some attention from my human colleagues feel free to reopen it.