Как избавиться от ошибки в тестах Invalid JSON was returned from the route?

У меня код теста
public function testRegisterValidate()
    {
        $responseString = $this->json('POST', '/api/register', ['email' => 'Hello']);
        $responseString
            ->assertStatus(200)
            ->assertJsonStructure([
                'error',
                'success',
                'message' => ['email', 'password'],
                'response'
            ]);
    }

В ответ я получаю
{"error":400,"success":false,"message":"Неверный формат email.","response":[]}

Почему у меня срабатывает ошибка и как проверить метод?
public function register(Request $request)
    {
        $validate = $this->validator($request->all());
        $value = '';
        if ($validate){
            $value = ResponseApi::response([], 400, false, 400, $validate);
        }

        return $value;
    }

protected function validator(array $data) :string
    {
        $validator = Validator::make($data, [
            'email' => 'required|email|string|max:255|unique:users',
            'password' => 'required|string|min:6'
        ]);

        if($validator->fails()){
            return $validator->errors()->first();
        };
    }

ResponseApi
public static function response(array $response = [], int $status = 200, bool $success = true, int $error = null, string $message = '', array $headers = [])
    {
        $headers += ['Content-type' => 'application/json; charset=utf-8'];

        $response = [
            'error' => $error,
            'success' => $success,
            'message' => $message,
            'response' => $response ? $response : [],
        ];

        return response()->json($response, $status, $headers, JSON_UNESCAPED_UNICODE);
    }


Полностью ошибка звучит
Invalid JSON was returned from the route.
 /home/ruslan/Разработка/implantBackend/vendor/laravel/framework/src/Illuminate/Foundation/Testing/TestResponse.php:695
 /home/ruslan/Разработка/implantBackend/vendor/laravel/framework/src/Illuminate/Foundation/Testing/TestResponse.php:507
 /home/ruslan/Разработка/implant_city_backend/tests/Unit/Auth/ApiAuthControllerTest.php:35
 /home/ruslan/Разработка/implant_city_backend/vendor/phpunit/phpunit/src/TextUI/Command.php:206
 /home/ruslan/Разработка/implant_city_backend/vendor/phpunit/phpunit/src/TextUI/Command.php:162


->assertHeader('Content-type', 'application/json; charset=utf-8')

Header [Content-type] was found, but value [text/html; charset=UTF-8] does not match [application/json; charset=utf-8].
Failed asserting that two strings are equal.
Expected :'application/json; charset=utf-8'
Actual   :'text/html; charset=UTF-8'
  • Вопрос задан
  • 3457 просмотров
Решения вопроса 1
difiso
@difiso
В параллельной вселенной я космонавт
У вас в валидаторе же написано:
'email' => 'required|email|string|max:255|unique:users',

что-то мне подсказывает, что 'Hello' - слегка невалидный e-mail адрес!

И да. Если у вас есть валидатор 'email', то 'string' можно опустить, да и ограничивать длину адреса так себе практика!
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы