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\Api\Security;

use ApiPlatform\Symfony\Bundle\Test\ApiTestCase;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Contracts\HttpClient\ResponseInterface;

use function Symfony\Component\String\u;

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.',
        ]);
        self::assertJsonContains([
            '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

  Work with me!


Call to action

Did you like this post? You can help me back in several ways: (use the "reply" link on the right to comment or to contact me )

Thank you for reading! And see you soon on Strangebuzz! 😉

COil