minaremonshaker's avatar

Laravel Test Fails: RefreshDatabase vs DatabaseTruncation with assertJsonCount on Search API

Hello, I want to understand why this test fails specifically with the RefreshDatabase trait but succeeds with DatabaseTruncation. The failing assertion is $response->assertJsonCount(1, 'data')—all other assertions and the complete test method work fine.

I've tested other database traits, but none resolve the issue. Here's the test code:

0 likes
5 replies
Tray2's avatar
Tray2
Best Answer
Level 73

It fails because of this line $user = $users->find(1);

When you refresh the database, you don't reset the internal sequence of the id. That means that the first time you run it, it creates id 1, and 2, the next time it creates id 3 and 4, and so on.

Truncating the table resets the internal sequence, thus giving you id 1 and 2 every time you run the test.

So changing the line to

$user = $user->first();

Or to

$user = $user->find($users[0]->id);

Should solve your issue.

minaremonshaker's avatar

hi ,

i have implemented what you said in the post above but it still fails , included in my post here the

1-test method 2-test result from the console

    public function users_search_returns_results_for_existing_data(array $payload)
    {

        $users = User::factory()->createMany($payload);

        $user = $users->find($users[0]->id);

        $response = $this
            ->withHeader("Accept", 'application/json')
            ->actingAs($user)
            ->getJson(route('authors.index', ['search' => 'b']));

        $response->assertStatus(200);

        $response->assertJsonCount(1, 'data');

    }

test Results

/bin/php /home/mina/Desktop/Tickets/vendor/phpunit/phpunit/phpunit --configuration /home/mina/Desktop/Tickets/phpunit.xml --filter "/(Tests\\Feature\\AuthorTest::users_search_returns_results_for_existing_data)( .*)?$/" --test-suffix AuthorTest.php /home/mina/Desktop/Tickets/tests/Feature --teamcity
Testing started at 2:03 AM ...
PHP Warning:  PHP Startup: Unable to load dynamic library 'couchbase' (tried: /usr/lib/php/20240924/couchbase (/usr/lib/php/20240924/couchbase: cannot open shared object file: No such file or directory), /usr/lib/php/20240924/couchbase.so (/usr/lib/php/20240924/couchbase.so: cannot open shared object file: No such file or directory)) in Unknown on line 0
PHPUnit 11.5.46 by Sebastian Bergmann and contributors.

Runtime:       PHP 8.4.15
Configuration: /home/mina/Desktop/Tickets/phpunit.xml

Failed to assert that the response count matched the expected 1
Failed asserting that actual size 0 matches expected size 1.
/home/mina/Desktop/Tickets/vendor/laravel/framework/src/Illuminate/Testing/AssertableJsonString.php:74
/home/mina/Desktop/Tickets/vendor/laravel/framework/src/Illuminate/Testing/TestResponse.php:1006
/home/mina/Desktop/Tickets/tests/Feature/AuthorTest.php:81

Time: 00:07.109, Memory: 44.50 MB

There was 1 failure:

1) Tests\Feature\AuthorTest::users_search_returns_results_for_existing_data with data set "users_to_create" ([['mina', 'remon', '[email protected]', 'mina20088'], ['beshoy', 'shaker', '[email protected]', 'beshoy20088']])
Failed to assert that the response count matched the expected 1
Failed asserting that actual size 0 matches expected size 1.

/home/mina/Desktop/Tickets/vendor/laravel/framework/src/Illuminate/Testing/AssertableJsonString.php:74
/home/mina/Desktop/Tickets/vendor/laravel/framework/src/Illuminate/Testing/TestResponse.php:1006
/home/mina/Desktop/Tickets/tests/Feature/AuthorTest.php:81

FAILURES!
Tests: 1, Assertions: 2, Failures: 1.
Process finished with exit code 1
Tray2's avatar

Try

  public function users_search_returns_results_for_existing_data(array $payload)
    {

        $users = User::factory()->createMany($payload);
		
		dd($users);
        
		$user = $users->find($users[0]->id);

        $response = $this
            ->withHeader("Accept", 'application/json')
            ->actingAs($user)
            ->getJson(route('authors.index', ['search' => 'b']));

        $response->assertStatus(200);

        $response->assertJsonCount(1, 'data');

    }

To make sure you have a user, and then you can try,

$user = User::find($users[0]->id);
minaremonshaker's avatar

hi i still have the same problem here , below is another test that i have tried , this test dose not work unless i used the DatabaseTruncation triat in my test class , this is confusing

minaremonshaker's avatar

I want to add something that I am using MySQL for testing and not SQLite , I don't know if this would change something , also RefreshDatabase trait worked when I switched to SQLite

Please or to participate in this conversation.