React / DevOps Showcase (Part 3)

In part 2 we did some front end unit tests for React using Jest + Enzyme. The last component I wanted to get some experience with is doing testing with Laravel directly.

Currently, the only live endpoints we have are for the grocery list. So this is what I will test!

First we need to make a new test:

php artisan make:test GroceriesTest

And then I created a simple test:

 public function test_get_groceries()
     {
         $response = $this->getJson('/api/groceries');
 
         $response->assertStatus(200) // ensure we get a 200 - Success Status code
                  -> assertJsonStructure(['*' => [
                      'id',
                      'item',
                      'is_completed',
                      'created_at',
                      'updated_at'
                  ]]);    // ensure we get a json response in the following format
     }   

This test verifies the endpoint returns a 200 status code and that each grocery item follows a particular format.

I tried running php artisan test and ./vendor/bin/phpunit from my project’s base directory, however both failed for me. So if anyone has any advice on how to make that work let me know. I am on Laravel 8.x and I even modifed my phpunit.xml to just look for all PHP files in the ./tests directory but it still did not work.

I can still manually run it like so, and it passed!

Here is the code for this commit.

One of the next things I would like to figure out is ci/cd or creating a pipeline. On my GitHub repo, under actions, I can see we already have some preset ones:

I will go ahead and start with the Laravel workflow, leave the default settings and commit. I can see that it already goes back through my prior commits and is running it through the workflow, now they are failing:

Time for some troubleshooting! We can see here that my name of react-devops-showcase does not meet the spec of vendor-name/project-name so I changed that to ericturner/react-devops-showcase and composer validates the file! Let’s push the commit and see if we can build.

We did finally get further in the build, but now our unit test we just made is failing. The api endpoint is returning a 500 error instead of the 200. My guess is because it’s copying the .env.example to .env and that example file is set using a mysql and not sqlite. Let’s fix that and push another commit.

Still nothing. I added a new line to give us some more useful information, $this->withoutExceptionHandling(); and now it is saying the db table cannot be found:

It looks like we will need to add a seeder to get some data in the database, and then re-configure our pipeline to seed the database! Generating a seeder can be done by running php artisan make:seeder <SeederName> and then we can run it with php artisan db:seed.

I made a simple seeder to just generate 5 random / wacky grocery items to our database:

<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;

class GroceriesSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        //dummy adjectives and items
        $modifier = ['Chocolate', 'Vanilla', 'Strong', 'Dairy-Free', 'Gluten Free', 'Soft'];
        $items = ['Milk', 'Cookies', 'Bread', 'Butter', 'Dish Soap', 'Towels'];

        // empty table
        DB::table('groceries')->truncate();
        
        // generate 5 fresh records
        for ($records=0; $records < 5; $records++){
            // pick a random modifier and item and merge them together
            DB::table('groceries')->insert([
                'item'=> $modifier[rand(0, (count($modifier) - 1))] . ' ' . $items[rand(0, (count($items) - 1))]
            ]);
        }

        
    }
}

And running php artisan db:seed we can see it works!

Before I commit, I also edited the `./.github/laravel.yml file to have two new steps: Run Migrations and Seed Data:

jobs:
    ...
    steps:
        ...
    - name: Run Migrations
      run: php artisan migrate:fresh
    - name: Seed Data
      run: php artisan db:seed
        ...

And it worked!

Writing a seeder, and adding those two steps to our pipeline allowed the built to succeed!

Conclusion


This has been an exciting project for me to work on! I have learned how to:

  • build a Laravel / React project from scratch (using composer)
  • use git commands to push, pull, add & commit (also with gpg key verification!)
  • use Laravel’s php artisan commands to generate models, controllers, seeders, make migrations, seed the db and serve a dev app
  • use Jest + Enzyme to do unit-testing on front-end React Components
  • use PHPUnit to do unit-testing on back-end Laravel API endpoints
  • use GitHub actions to build a custom pipeline that can build my project from scratch, seed the database and run my PHPUnit tests
  • use GitHub to push a release at the current state of this repo

Comments

No comments available.

Leave a Reply

Your email address will not be published. Required fields are marked *