phpunit-snapshot-assertions icon indicating copy to clipboard operation
phpunit-snapshot-assertions copied to clipboard

Allow passing variables to Snapshot to enable dynamic responses

Open chr-hertel opened this issue 1 year ago • 0 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.

chr-hertel avatar Mar 28 '24 07:03 chr-hertel