Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Test Bundle Laravel Package

desarrolla2/test-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require desarrolla2/test-bundle
    

    Ensure your project uses Symfony 5.x/6.x (last release was 2023-02-07).

  2. First Test Class: Extend Desarrolla2\TestBundle\Functional\WebTestCase in your test class:

    namespace App\Tests\Functional;
    use Desarrolla2\TestBundle\Functional\WebTestCase;
    
    class ExampleTest extends WebTestCase
    {
        public function testBasicRoute()
        {
            $client = $this->getClient();
            $this->requestAndAssertOkAndHtml($client, 'GET', '/some-route');
        }
    }
    
  3. Key Methods to Explore:

    • getClient(): Returns a Symfony Client instance.
    • logIn($client, $email, $roles): Authenticates a user (requires getBackendRoles() helper).
    • requestAndAssertOkAndHtml(): Asserts HTTP 200 + HTML response.
    • requestGetAndPostAndAssertRedirect(): Tests form submissions with redirects.
  4. Where to Look First:

    • Review the examples in the README for common use cases.
    • Check src/Functional/WebTestCase.php for all available helper methods.

Implementation Patterns

Common Workflows

1. Authenticated Requests

public function testProtectedRoute()
{
    $client = $this->getClient();
    $this->logIn($client, 'user@example.com', ['ROLE_ADMIN']);
    $this->requestAndAssertOkAndHtml($client, 'GET', '_app.admin.dashboard');
}
  • Tip: Cache getClient() and $user if testing multiple endpoints for the same user.

2. Form Submission Testing

public function testFormValidation()
{
    $client = $this->getClient();
    $this->logIn($client, 'user@example.com', []);

    $this->requestGetAndPostAndAssertRedirect(
        $client,
        '_app.contact.submit',
        ['name' => 'Test User', 'email' => 'test@example.com']
    );
}
  • Pattern: Use requestGetAndPostAndAssertRedirect for forms that redirect on success.

3. API Endpoint Testing

public function testApiEndpoint()
{
    $client = $this->getClient();
    $client->request('GET', '/api/endpoint', [
        'headers' => ['Content-Type' => 'application/json']
    ]);
    $this->assertEquals(200, $client->getResponse()->getStatusCode());
    $this->assertJson($client->getResponse()->getContent());
}
  • Note: The bundle is Symfony-focused; use raw Client methods for non-HTML/API responses.

4. Data Fixtures

protected function setUp(): void
{
    parent::setUp();
    $this->loadFixtures([
        'App\DataFixtures\UserFixture',
        'App\DataFixtures\ProductFixture'
    ]);
}
  • Integration: Combine with Symfony’s DatabaseTestCase or DoctrineFixturesBundle for test data.

5. Custom Assertions

protected function assertResponseContains($text)
{
    $this->assertStringContainsString($text, $this->getClient()->getResponse()->getContent());
}
  • Tip: Extend WebTestCase to add reusable assertions.

Integration Tips

  1. Symfony Kernel:

    • Override getKernel() in your test class if using a custom kernel:
      protected static function getKernelClass(): string
      {
          return CustomKernel::class;
      }
      
  2. Environment Configuration:

    • Use .env.test for test-specific settings (e.g., database, cache):
      symfony console --env=test cache:clear
      
  3. Parallel Testing:

    • The bundle doesn’t support parallel tests natively. Use Symfony’s ParallelTestCase if needed.
  4. Debugging:

    • Dump the response for complex assertions:
      $response = $this->getClient()->getResponse();
      file_put_contents('debug.html', $response->getContent());
      

Gotchas and Tips

Pitfalls

  1. Deprecated Methods:

    • The package is archived (last release: 2023-02-07). Assume no future updates.
    • Example: requestAndAssertOkAndHtml may not handle newer Symfony Client changes.
  2. Authentication Quirks:

    • logIn() relies on Symfony’s security system. Ensure your firewall is configured correctly.
    • Error: Invalid credentials may occur if the user provider isn’t set up for tests.
  3. Route Naming:

    • The bundle expects Symfony’s _app. route naming convention (e.g., _app.activity.index).
    • Fix: Use router->generate() if routes are named differently:
      $url = $this->getClient()->getContainer()->get('router')->generate('activity.index');
      
  4. HTML Assertions:

    • requestAndAssertOkAndHtml checks for text/html content type. False negatives may occur with:
      • SPAs (React/Vue) returning HTML-wrapped JSON.
      • Partial responses (e.g., Turbo/HTMX).
  5. Fixture Loading:

    • Fixtures loaded in setUp() may not persist across tests. Use transactions or DatabaseTestCase.

Debugging Tips

  1. Client State:

    • Reset the client between tests to avoid state leaks:
      $client = static::createClient([], [
          'PHP_AUTH_USER' => 'user',
          'PHP_AUTH_PW'   => 'pass',
      ]);
      
  2. Response Inspection:

    $response = $this->getClient()->getResponse();
    dump([
        'status' => $response->getStatusCode(),
        'headers' => $response->headers->all(),
        'content' => $response->getContent(),
    ]);
    
  3. Slow Tests:

    • Disable debug mode for faster tests:
      $client = static::createClient(['environment' => 'test', 'debug' => false]);
      

Extension Points

  1. Custom Assertions:

    namespace App\Tests\Functional;
    use Desarrolla2\TestBundle\Functional\WebTestCase;
    
    class CustomWebTestCase extends WebTestCase
    {
        protected function assertResponseHasElement($selector)
        {
            $this->assertSelectorTextContains('css', $selector, 'Expected element');
        }
    }
    
  2. Override logIn:

    protected function logIn($client, $email, $roles)
    {
        // Custom logic (e.g., API token auth)
        $client->request('POST', '/api/login', [
            'json' => ['email' => $email, 'password' => 'password']
        ]);
        return $this->getUserFromResponse($client);
    }
    
  3. Mock Services:

    • Use Symfony’s container.get() to replace services in tests:
      $this->getClient()->getContainer()->set('app.mailer', $this->createMock(Mailer::class));
      
  4. Event Listeners:

    • Attach listeners to the test client for side effects:
      $client = static::createClient();
      $client->getContainer()->get('event_dispatcher')->addListener(
          KernelEvents::REQUEST,
          [$this, 'onKernelRequest']
      );
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor
spatie/laravel-javascript-views