AssertableJson->whereNot does not work with array.
Laravel Version
10.43.0
PHP Version
8.3.2 on Docker
Database Driver & Version
No response
Description
I came across a strange behavior of whereNot method in Illuminate\Testing\Fluent\Concern\Matching trait and I cannot understand if it's wanted or not.
I tried to test the emptiness of an array in a response and I used the whereNot method with an AssertableJson object. Therefore I passed to the function an empty array because I seen the implementation and I noticed that on line 73 of Matching trait there is a conversion of $expected var from an Arrayable to an array, so I supposed that the rational behind was to manage array too. But on line 86 the $expected var it's not convert to string for sprintf so php throw an ErrorException: Array to string conversion.
I add an example that throw as I mentioned above in the Steps to reproduce section.
Steps To Reproduce
<?php
use Illuminate\Testing\TestResponse;
use Illuminate\Http\Response;
use Illuminate\Testing\Fluent\AssertableJson;
test('whereNot should not throw an error', function () {
$response = new TestResponse(new Response('{"data": [1, 2, 3]}'));
$response->assertJson(function (AssertableJson $json) {
$json->whereNot('data', []);
});
});
Thank you for reporting this issue!
As Laravel is an open source project, we rely on the community to help us diagnose and fix issues as it is not possible to research and fix every issue reported to us via GitHub.
If possible, please make a pull request fixing the issue you have described, along with corresponding tests. All pull requests are promptly reviewed by the Laravel team.
Thank you!
Hi @FunkyOz,
From what I've gathered, while the Matching::whereNot() method does allow for an array to be passed, it seems to assume that it is a non-empty array. If your intention is to simply check that the value located at $key is non-empty, then there are other methods such as has() that already serve a similar enough purpose (https://laravel.com/docs/10.x/http-tests#asserting-json-attribute-presence-and-absence).
It's hard to determine the author's original intent just from observing the code though, so in the case that Matching::whereNot() was in fact intended to allow for empty arrays to be passed, then I think a simple (but admittedly hacky) solution to the issue would just be to call json_encode($expected) before passing it to sprintf().
Hope this helps :)
Hi @calvinli08, I found a workaround for my use case so no problem, I opend this issue only for clarification and you were helpful. If you want to close the issue, it's ok.
Thank you :)
This looks like an obvious bug, as even non-empty array will result in an error, so I would like to fix it if no one else is handling. I also think the solution is to put json_encode($expected) before sprintf().
Thank you
Looks like @FunkyOz found a solution so closing this one. Thanks all.