joshgallagher24
2 years ago
119
1
Lumen

Testing Fractal Transformer in Lumen

Posted 2 years ago by joshgallagher24

This is Lumen specific.

I am currently creating an API with spatie's package fractalistic.

I am building it using TDD, but I am finding it hard to find the best method of testing them.

My first approach was to create a feature test for getting a collection of articles from the index endpoint.

ArticleTransformer.php

<?php

namespace App\Transformers;

use App\Models\Article;

class ArticleTransformer extends Transformer
{
    /**
     * Transform the given article collection into JSON.
     *
     * @param  Article $article
     * @return array
     */
    public function transform(Article $article)
    {
        return [
            'title' => $article->title,
            'slug' => $article->slug,
            'teaser' => $article->teaser,
            'body' => $article->body,
            'created_at' => $article->created_at,
            'updated_at' => $article->updated_at,
        ];
    }
}

ArticleTest.php

<?php

namespace Tests\Feature;

use Tests\TestCase;
use App\Models\User;
use App\Models\Article;

class ArticleTest extends TestCase
{
    /**
     * @test
     */
    public function a_collection_of_articles_are_returned_as_json()
    {
        factory(User::class)->create();
        $articles = factory(Article::class, 4)->create();

        $this->json('GET', '/articles')
            ->seeJsonStructure([
                'data' => [[
                    'title',
                    'slug',
                    'teaser',
                    'body',
                    'created_at',
                    'updated_at'
                ]]
            ])
            ->assertResponseStatus(200);
    }
}

In ArticleTest.php, I use "seeJsonStructure" to test that the structure is correct, I use this because Lumen's "seeJson" requires an array to be passed - fractal returns json wrapped in 'data'. However, I unsure if theres a better approach like testing a Transformer directly?

Anybody have any experience testing transformers?

Please sign in or create an account to participate in this conversation.