troccoli's avatar

Laravel Pennant and Cypress tests

I'm using Laravel Pennant to manage feature flags.

Pest tests are easy to write, but I'm struggling to write E2E tests in Cypress. Specifically, I can't find a nice way to toggle a feature on (they are off by default) just of one test.

Has anybody written some Cypress tests for features using Pennant? Does anybody have any suggestions how I could achieve this?

0 likes
1 reply
LaryAI's avatar
Level 58

Certainly! Here’s how you can approach toggling Laravel Pennant feature flags for Cypress E2E tests:

Problem Recap

  • You want to enable a Pennant feature flag for a specific Cypress test.
  • Feature flags are off by default.
  • You need a way to toggle them just for the duration of a test.

Solution

1. Create a Test-Only Route to Set Feature Flags

In your Laravel app, add a route that allows you to enable/disable a feature flag for the currently authenticated user (or globally, if needed). Restrict this route to only be available in non-production environments.

Example:

// routes/test-feature-flags.php

use Illuminate\Support\Facades\Route;
use Laravel\Pennant\Feature;

Route::post('/test/feature-flags', function () {
    abort_unless(app()->environment('local', 'testing'), 403);

    $feature = request('feature');
    $enabled = request('enabled', true);

    if ($enabled) {
        Feature::forUser(auth()->user())->activate($feature);
    } else {
        Feature::forUser(auth()->user())->deactivate($feature);
    }

    return response()->json(['feature' => $feature, 'enabled' => $enabled]);
});

Register this route only in local/testing:

// routes/web.php

if (app()->environment('local', 'testing')) {
    require __DIR__.'/test-feature-flags.php';
}

2. Use Cypress to Toggle the Feature

In your Cypress test, after logging in (if needed), make a request to this route to enable the feature flag.

Example:

// cypress/support/commands.js

Cypress.Commands.add('setFeatureFlag', (feature, enabled = true) => {
  cy.request('POST', '/test/feature-flags', {
    feature,
    enabled,
  });
});

3. Use in a Cypress Test

// cypress/e2e/your-feature.cy.js

it('shows the new feature when enabled', () => {
  cy.login(); // however you handle authentication
  cy.setFeatureFlag('your-feature-flag', true);

  cy.visit('/some-page');
  cy.contains('New Feature Content').should('exist');
});

4. Clean Up (Optional)

If you want to reset the flag after the test, you can call cy.setFeatureFlag('your-feature-flag', false) in an afterEach block.


Summary

  • Add a test-only route to toggle feature flags.
  • Use Cypress to hit this route before your test.
  • This allows you to control Pennant flags per test, just like you do in Pest.

Note: Never expose this route in production!


Let me know if you need a more tailored example for your specific setup!

Please or to participate in this conversation.