Fix http testing validation error 320
Problem:
In laravel 10 app I have a test method :
public function testAdded() { // Test Data Setup $tagModel = Tag::factory()->make([]); // model only in memory
// Test Action // $tagModel->name = ''; $response = $this ->post(route('tags.store'), $tagModel->toArray()); $response ->assertStatus(201);
// READ TAG CREATED ABOVE $insertedTag = Tag::getBySearch(search: $tagModel->name, partial: false) ->first();
$this->assertNotNull($insertedTag, 'Inserted tag not found'); $this->assertEquals( $insertedTag->name, $tagModel->name, 'Name read is not equal name on insert' ); } |
and it works ok, untill I uncommented line with :
I got error :
├ Expected response status code [201] but received 302. ├ Failed asserting that 201 is identical to 302. ├ ├ The following errors occurred during the last request: ├ ├ The name field is required. │
|
I got valid error message, but why code is 302?
I read in net :
The HTTP response status code 302 Found is a common way of performing URL redirection. The HTTP/1.0 specification (RFC 1945) initially defined this code, and gave it the description phrase "Moved Temporarily" rather than "Found". |
I expecte error 400(bad rerquest)
On route 'tags.store' control action is assigned with common Request class as :
public function store(CreateTagRequest $request) { try { $tag = $this->tagCrudRepository->store(data: $request->only('name')); return response()->json(['tag' => (new TagResource($tag))], 201); } catch (\Error | \Exception $e) { \Log::info($e->getMessage()); return response()->json([ 'error_message' => $e->getMessage(), ], 500); } |
and common array of rules in above class :
[ 'name' => [ 'required', 'string', 'max:100', ], ] |
Why I got 302 code ? Is my test invalid ?
Solution:
From the comments you seems sending JSON Requests:
instead of post():
$response = $this ->post(route('tags.store'), $tagModel->toArray()); |
use postJson():
$response = $this ->postJson(route('tags.store'), $tagModel->toArray()); |
More Information in the >Laravel Doc - Testing JSON APIS
Answered by: >PsyLogic
Credit: >Stackoverflow
Suggested Blogs:
>How to create a One Page App with Angular.js, Node.js and MongoDB?
>Complete guide to Perform crud operation in angular using modal popup
>What is data binding in Angular?
>How To Create Nested Table Structure In Angular?