sylvain92's avatar

unit test view::share return

hi i try to test unit but view::share trigger an issue

ErrorException: Undefined variable: $newestPosts

here my code

in PageTest

public function testHomepage()
    {
        $this->withoutExceptionHandling();
        $response = $this->get('/');

        $response->assertStatus(200);
    }

in app.blade.php

 @foreach($newestPosts as $post)
   <a href="{{ route('communities.posts.show', [$post->id]) }}">{{ $post->title }}</a>
   <div class="mt-1">{{ $post->created_at->diffForHumans() }}</div>
   <hr />
@endforeach

in AppServiceProvider

View::share('newestPosts', Post::with('community')->latest()->take(5)->get());
0 likes
6 replies
bugsysha's avatar

Error says that you have $newPosts variable somewhere, and you pass $newestPosts to views. Search in your code for newPosts and change it to newestPosts.

sylvain92's avatar

no it's my typo error, var is now correct for the question

sylvain92's avatar

hi no it's just my error, fix but issue is same

$newestPosts come from view::share on boot, inside appServiceProvider

when start unit test, i dont know if blade understand, if data come from this view::share

martinbean's avatar

@sylvain92 Make it a feature test. This isn’t a unit test.

A unit test extends PHPUnit’s TestCase class so won’t boot the framework, therefore you won’t have access to methods like $this->get.

sylvain92's avatar

Hi i switch to Feature test, but have same issue. it seems Tests\Features not instantiate data while boot the framework

because $newestPost get from AppServiceProvider , not from controller

<?php

namespace Tests\Feature;

use Tests\TestCase;
use App\Models\Post;
use App\Models\Community;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;

class PageTest extends TestCase
{
    use RefreshDatabase;
    protected $seed = true;

  
    public function testHomepage()
    {
        $this->withoutExceptionHandling();
        $response = $this->get('/');
        $response->assertStatus(200);
    }

Please or to participate in this conversation.