Testing a JSON login with the API-Platform ApiTestCase class

Published on 2021-10-31 • Modified on 2021-10-31

In this snippet, we see how to test a JSON login with the API-Platform ApiTestCase class. We pass the username and password with the json option; then, e can convert the response to an array to get the security token.


<?php

declare(strict_types=1);

namespace App\Tests\Security;

use ApiPlatform\Core\Bridge\Symfony\Bundle\Test\ApiTestCase;
use Symfony\Component\HttpFoundation\Response;
use function Symfony\Component\String\u;
use Symfony\Contracts\HttpClient\ResponseInterface;

final class JsonLoginTest extends ApiTestCase
{
    public function testLoginOK(): void
    {
        $response = $this->login('reader', 'test');
        self::assertResponseIsSuccessful();
        $arrayResponse = $response->toArray();
        self::assertArrayHasKey('token', $arrayResponse);
        self::assertNotTrue(u($response->toArray()['token'])->isEmpty());
    }

    public function testLoginNOK(): void
    {
        $this->login('reader', 'wrong password');
        self::assertResponseStatusCodeSame(Response::HTTP_UNAUTHORIZED);
        self::assertResponseHeaderSame('content-type', 'application/json');
        self::assertJsonEquals([
            'code' => Response::HTTP_UNAUTHORIZED,
            'message' => 'Invalid credentials.',
        ]);
    }

    /**
     * JSON Login try with a given email and password.
     */
    public function login(string $username, string $password): ResponseInterface
    {
        return self::createClient()->request('POST', '/api/login_check', [
            'json' => compact('username', 'password'),
        ]);
    }
}

 More on Stackoverflow   Read the doc  More on the web  Random snippet