Laravel: View::share(...) with $response->assertViewHas(...) in phpunit - laravel

I share my params with view like this:
\Illuminate\Support\Facades\View::share('params', $params);
view()->share('params', $params);
and testing it with phpunit like so
$response = $this->actingAs($user)->get($url);
$response->assertViewHas('params');
And I'm getting this FAILURE
Failed asserting that an array has the key 'params'.
When I share like so, phpunit is green
return view('account', compact('params'));
How can I test variables shared with view()->share('params', $params); ?
I'm using Laravel 5.8

Related

Why I receive "CSRF token mismatch" while running tests in laravel?

I want to run my tests without receiving "CSRF token mismatch" exceptions. In the laravel documentation is noted that:
The CSRF middleware is automatically disabled when running tests.
the line of code where the exception is thrown looks like this:
$response = $this->json('POST', route('order.create'), [
'product_id', $product->id
]);
and for running tests I am working in my zsh terminal:
php artisan test --env=testing
This is my test class:
<?php
namespace Tests\Feature;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Tests\TestCase;
class SessionCartTest extends TestCase
{
public function testExample()
{
$product = \App\Product::inRandomOrder()->first();
$response = $this->postJson(route('order.insert'), [
'product_id' => $product->id,
]);
$response->assertStatus(200); // here I receive 419
}
}
What am I doing wrong and how could I fix this? I am using laravel 7.
I ran into this problem x times now and each time I fix it by running:
php artisan config:clear
Probably the APP_ENV is not being set to testing.
You can set a ENV variable in the command line by preceding the php command.
So on your case set the environment to testing and run the artisan command by:
APP_ENV=testing php artisan test
Your data array is wrong. Try the following change:
$response = $this->postJson(route('order.insert'), [
'product_id' => $product->id, // use the arrow notation here.
]);
When you are running tests on Docker where the APP_ENV is hard coded with other values than testing (dev, local) in docker-compose.yaml file, phpunit cannot execute tests properly.
You will need to delete the all APP_ENV in docker files.
This works by setting a custom csrf-token
$this
->withSession(['_token' => 'bzz'])
->postJson('/url', ['_token' => 'bzz', 'other' => 'data']);

Laravel Testing for update user data when logged in

I am doing feature testing for my Laravel application. I am trying to update an authenticated user data. I am using actingAs to authenticate my user in my test code and then trying to post with some data to update that user data. But I am getting "Call to a member function update() on null" error.
This problem only happening on test case. original application working fine.
public function an_authenticated_account_user_with_valid_role_can_change_2fa_option()
{
$this->withoutExceptionHandling();
//preventing middlewares
$this->withoutMiddleware(\App\Application\Middleware\VerifyCsrfToken::class);
$attributes = [
'two_step' => 'no'
];
$response = $this->actingAs($this->validRoleUser, 'account')
->post('/account/security/change-2fa', $attributes);
$response->assertStatus(200);
$response->assertSee('Please select an option');
}
I am getting this error message during test above code:
Call to a member function update() on null

laravel route parameters return null on unittest

I got a problem on phpunit
I'm design route as
/v1/outlet/{outlet_id}/test
Route::get('outlets/{outlet_id}/test', ['as' => 'test'], function(){
return app('request')->route('outlet_id');
});
It's working when i call it in postman or brower
but in phpunit show out as error
Call to a member function parameter() on array
test code
$req = $this->call('GET', '/v1/outlets/1/test');
$this->assertResponseStatus(200);
You have outlets plural in your test but outlet singular in your route definition.
Please remove the code use WithoutMiddleware from your testing class if it is there and try.

consuming web service with laravel and guzzle

I'm trying to retrieve some information on my controller
using GuzzleHttp
use \GuzzleHttp\Client;
class ClientsController extends Controller
{
public function index()
{
$client = new Client(['base_uri' => 'http://localhost/systeml/public/ws/clients']);
$response = $client->request('GET', '');
$contents = $response->getBody()->getContents();
dd($contents);
}
when I run this command the following problem appears
(1/1) ServerException Server error: GET
http://localhost/systeml/public/ws/clients
resulted in a 500 Internal Server Error response:
the guzzle is running normal and having problems trying to access the other local server?
Make sure in the other project you run php artisan serve in the root directory of the project.
And use postman also.

PHPUnit - post to an existing controller does not return an error

I am new to PHPUnit and TDD. I just upgrade my project from Laravel 5.4 to 5.5 with phpunit 6.5.5 installed . In the learning process, I wrote this test:
/** #test */
public function it_assigns_an_employee_to_a_group() {
$group = factory(Group::class)->create();
$employee = factory(Employee::class)->create();
$this->post(route('employee.manage.group', $employee), [
'groups' => [$group->id]
]);
$this->assertEquals(1, $employee->groups);
}
And I have a defined route in the web.php file that look like this
Route::post('{employee}/manage/groups', 'ManageEmployeeController#group')
->name('employee.manage.group');
I have not yet created the ManageEmployeeController and when I run the test, instead of get an error telling me that the Controller does not exist, I get this error
Failed asserting that null matches expected 1.
How can I solve this issue please?
The exception was automatically handle by Laravel, so I disabled it using
$this->withoutExceptionHandling();
The test method now look like this:
/** #test */
public function it_assigns_an_employee_to_a_group() {
//Disable exception handling
$this->withoutExceptionHandling();
$group = factory(Group::class)->create();
$employee = factory(Employee::class)->create();
$this->post(route('employee.manage.group', $employee), [
'groups' => [$group->id]
]);
$this->assertEquals(1, $employee->groups);
}
You may not have create the method in the Controller but that doesn t mean your test will stop.
The test runs.It makes a call to your endpoint. It returns 404 status because no method in controller found.
And then you make an assertion which will fail since your post request
wasn't successful and no groups were created for your employee.
Just add a status assertion $response->assertStatus(code) or
$response->assetSuccessful()

Resources