Last active
January 26, 2022 18:23
-
-
Save kutnickclose/21522e635e26f4fee4c760d730a42e2d to your computer and use it in GitHub Desktop.
Cypress + Launchdarkly
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 astring
, but accepts anobject
of feature flags + values: