Skip to content

Instantly share code, notes, and snippets.

@kutnickclose
Last active January 26, 2022 18:23
Show Gist options
  • Save kutnickclose/21522e635e26f4fee4c760d730a42e2d to your computer and use it in GitHub Desktop.
Save kutnickclose/21522e635e26f4fee4c760d730a42e2d to your computer and use it in GitHub Desktop.
Cypress + Launchdarkly
// all code in cypress/support/commands.ts
// Convert this file to a module for global namespace declaration
export {};
declare global {
namespace Cypress {
interface Chainable {
/**
* Custom command to set launchdarkly feature flag values.
* @example cy.updateFeatureFlags({ 'flag-name': false})
*/
updateFeatureFlags(value: string): Chainable<Element>;
}
}
}
// Cypress command to turn on a feature flag for launch darkly
Cypress.Commands.add('updateFeatureFlags', (featureFlags: { [key: string]: boolean }) => {
// turn off push (EventSource) updates from LaunchDarkly
cy.intercept({ hostname: /.*clientstream.launchdarkly.com/ }, (req) => {
req.reply('data: no streaming feature flag data here\n\n', {
'content-type': 'text/event-stream; charset=utf-8',
});
});
// ignore api calls to events endpoint
cy.intercept({ hostname: /.*events.launchdarkly.com/ }, { body: {} });
// return feature flag values in format expected by launchdarkly client
cy.intercept({ hostname: /.*app.launchdarkly.com/ }, (req) => {
const body = {};
Object.entries(featureFlags).forEach(([featureFlagName, featureFlagValue]) => {
body[featureFlagName] = { value: featureFlagValue };
});
req.reply({ body });
});
});
// usage
// must be in beforeEach (vs before) because intercepts are cleared before each test run
beforeEach(() => {
cy.updateFeatureFlags({ 'flag-name': true})
})
@andymerskin
Copy link

Thanks for this! Got my Cypress + LD setup working like a dream.

One tweak to the type declaration towards the top — your params for updateFeatureFlags is typed as a string, but accepts an object of feature flags + values:

declare global {
  namespace Cypress {
    interface Chainable {
      /**
       * Custom command to set LaunchDarkly feature flag values
       * @example cy.updateFeatureFlags({ flagName: false })
       */
      updateFeatureFlags(featureFlags: Record<string, boolean>): Chainable<Element>;
    }
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment