Search code examples
laraveltestingphpunitrelationshipeager-loading

How can create a test in laravel for check load relationships


 public function test_show_role_should_return_actions()
    {
        $this->actingAs($this->user, 'api');
        $this->withHeaders(['Accept' => 'application/json',])
            ->get(route('roles.show', ['role' => $this->role->id]))
            ->assertJsonStructure([
                "data" => [
                    "name",
                    "actions" => [
                        "name",
                        "code"
                    ]
                ]
            ]);
    }

when I run the test,I have this error:

  1. Tests\Feature\Role\RoleTest::test_show_role_should_return_actions Failed asserting that an array has the key 'name'. Even when I remove the "name",I get an error for the "actions" key.

This is data that I get form Postman


Solution

  •  public function test_show_role_should_return_actions()
        {
            $this->actingAs($this->user, 'api');
            $this->getJson(route('roles.show', ['role' => $this->role->id]))
                ->assertJsonStructure([
                'data' => [
                    '*' => [
                        'name',
                        'actions' => [
                            '*' => [
                                'name',
                                'code'
                            ]
                        ]
                    ]
                ]
            ]);
        }