Reputation: 1175
Attempting to write unit testing for some ui validation messages that come back formatted like the following and completely lost
Unprocessable Content
Cache-Control: no-cache, private
Content-Type: application/json
Date: Fri, 31 Dec 2021 15:55:48 GMT
{"errors":{"assets":["filename must have a value"],"questions":[],"targeting_sets":[],"lists":[]}}
there error response gets generated using the following function
private function errorResponse()
{
return response()->json([
'errors' => $this->errors,
], Response::HTTP_UNPROCESSABLE_ENTITY);
}
Would appreciate any help with how to properly write the test so if it response has filename must have a value
it will pass
Upvotes: 0
Views: 2380
Reputation: 439
If you are testing a rendered view in Laravel and want to assert the response contains some text, you could use "assertSee", something like this:
<?php
namespace Tests;
use Tests\TestCase;
class MyTest extends TestCase
{
public function test_my_feature()
{
$featureResponse = $this->withSession(['abc' => '123'])
->post('/my-feature-route', ['requestParam1' => 'hello']);
$featureResponse->assertStatus(200);
$featureResponse->assertSee('Your changes were successfully saved.');
}
}
Upvotes: 0
Reputation: 1357
You should be able to check if the session has a specific error using the assertSessionHasErrors
method.
$response->assertSessionHasErrors([
'assets' => 'filename must have a value'
]);
As other comments have pointed out: you are returning a custom json response. That means that the method above will not work. Use assertJsonPath
instead.
$response->assertJsonPath("errors.assets", "filename must have a value");
As matiaslauriti suggested, the best-practise to do validation in Laravel is through a FormRequest
or Validator
. That will also allow you to write your unit tests in a less-complicated manner.
Upvotes: 2