Search code examples
laravellaravel-7laravel-testing

How can I assert an instance of a ResourceCollection in Laravel?


I am working with a feature test and it's returning data correctly; all things are coming back correctly; and I'm at the final portion of my test.

I am struggling to assert that I'm getting back a ResourceCollection:

$this->assertInstanceOf(ResourceCollection::class, $response);

Here is the portion of my test:

MyFeature.php

...

$http->assertStatus(200)
        ->assertJsonStructure([
            'data' => [
                '*' => [
                    'type', 'id', 'attributes' => [
                        'foo', 'bar', 'baz',
                    ],
                ],
            ],
            'links' => [
                'first', 'last', 'prev', 'next',
            ],
            'meta' => [
                'current_page', 'from', 'last_page', 'path', 'per_page', 'to', 'total',
            ],
        ]);

    // Everything is great up to this point...
    $this->assertInstanceOf(ResourceCollection::class, $response);

The error I get back is:

Failed asserting that stdClass Object (...) is an instance of class "Illuminate\Http\Resources\Json\ResourceCollection".

I'm not sure what I should be asserting in this case. I am getting back a resource collection, what should I be using instead? Thank you for any suggestions!

EDIT

Thank you @mare96! Your suggestion lead me to another approach that seemed to work. Which is great but I'm not too sure I really understand why...

Here's my full test (including my final assertion):

public function mytest() {
    $user = factory(User::class)->create();

    $foo = factory(Foo::class)->create();

    $http = $this->actingAs($user, 'api')
        ->postJson('api/v1/foo', $foo);

    $http->assertStatus(200)
        ->assertJsonStructure([
            'data' => [
                '*' => [
                    'type', 'id', 'attributes' => [
                        'foo', 'bar', 'baz'
                    ],
                ],
            ],
            'links' => [
                'first', 'last', 'prev', 'next',
            ],
            'meta' => [
                'current_page', 'from', 'last_page', 'path', 'per_page', 'to', 'total',
            ],
        ]);

    $this->assertInstanceOf(Collection::class, $http->getOriginalContent());
}

Solution

  • As I said in the comment above, your content will be the instance of Collection.

    You can do it like that:

    $this->assertInstanceOf(Collection::class, $http->getOriginalContent());
    

    So, you can try to debug, to make it clearer, like this: Do dd($http); you should get an instance of Illuminate\Foundation\Testing\TestResponse not the same when you do $http->dump(); right?

    So you need to assert an instance of just content, not the whole response.

    I hope at least I helped a little.