0

I just want to test an easy input field but I get this error!

enter image description here

/** @test */
public function email_must_be_a_valid_email()
 {
   $response = $this->post('/api/contacts', array_merge($this->data(), ['email' => 'NOT AN EMAIL']));
   $response->assertSessionHasErrors('email');
 }


private function data()
{
  return [
          'name' => 'Test Name',
          'email' => 'test@hotmail.com',
          'birthday' => '05/14/1988',
          'company' => 'ABC String'
        ];
}

Thses are the Controller and the request rule. I hope u can help me with it.

class StoreController extends Controller
{
    public function store(ContactsRequest $request)
    {
        $data = $request->validated();
        Contact::create($data);
    }
}

public function rules()
    {
        return [
            'name' => 'required',
            'email' => 'required|email',
            'birthday' => 'required',
            'company' => 'required',
        ];
    }

I hope u can help me with it.

Mohsen
  • 260
  • 3
  • 14

2 Answers2

3

If you are using an api route then you should use

$response->assertJsonValidationErrors(['email']);

or

$response->assertInvalid(['email']);

which works for both JSON and session errors.

https://laravel.com/docs/8.x/http-tests#assert-invalid

maazin
  • 149
  • 4
0

Thanks for your tips. I've solved the problem! But this kind of error message does not help at all to find the solution quickly. The solution is that I need to be logged in to create contact and then validate form data. But the error message says something completely different!

protected $user;

protected function setUp(): void
{
   parent::setUp();
   $this->user = User::factory()->create();
   $this->user->createToken(Str::random(30))->plainTextToken;
}


/** @test */
public function email_must_be_a_valid_email()
{
   $this->actingAs($this->user);
   $response = $this->post('/api/contacts', array_merge($this->data(), ['email' => 'NOT AN EMAIL']));
   $response->assertSessionHasErrors('email');
}

enter image description here

Mohsen
  • 260
  • 3
  • 14