featureFlags.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. const { recorder, event } = require("codeceptjs");
  2. const Container = require("codeceptjs/lib/container");
  3. const defaultConfig = {
  4. defaultFeatureFlags: {},
  5. };
  6. const supportedHelpers = ["Playwright"];
  7. /**
  8. * This plugin will listen for setting feature flags and apply them at the moment of page loading.
  9. * In this case set feature flags will affect the whole code including models initialization,
  10. * and other similar parts that will run on the the scripts load.
  11. */
  12. module.exports = (config) => {
  13. const helpers = Container.helpers();
  14. let helper;
  15. for (const helperName of supportedHelpers) {
  16. if (Object.keys(helpers).indexOf(helperName) > -1) {
  17. helper = helpers[helperName];
  18. }
  19. }
  20. if (!helper) {
  21. console.error(`Feature flags is only supported in ${supportedHelpers.join(", ")}`);
  22. return;
  23. }
  24. const options = Object.assign({}, defaultConfig, helper.options, config);
  25. if (options.enable) return;
  26. let defaultValue;
  27. let ffs = {};
  28. function hasStepName(name, step) {
  29. return step && (name === step.name || hasStepName(name, step.metaStep));
  30. }
  31. event.dispatcher.on(event.test.before, async () => {
  32. ffs = { ...options.defaultFeatureFlags };
  33. });
  34. event.dispatcher.on(event.step.before, async (step) => {
  35. if (hasStepName("amOnPage", step)) {
  36. recorder.add("set feature flags", async () => {
  37. try {
  38. helper.page.once("requestfinished", () => {
  39. helper.page.evaluate(
  40. (config) => {
  41. if (!window.APP_SETTINGS) window.APP_SETTINGS = {};
  42. if (!window.APP_SETTINGS.feature_flags) window.APP_SETTINGS.feature_flags = {};
  43. window.APP_SETTINGS.feature_flags = {
  44. ...window.APP_SETTINGS.feature_flags,
  45. ...config.feature_flags,
  46. };
  47. if (typeof config.feature_flags_default_value === "boolean") {
  48. window.APP_SETTINGS.feature_flags_default_value = config.feature_flags_default_value;
  49. }
  50. },
  51. { feature_flags: ffs, feature_flags_default_value: defaultValue },
  52. );
  53. });
  54. } catch (err) {
  55. console.error(err);
  56. }
  57. });
  58. }
  59. if (hasStepName("setFeatureFlags", step)) {
  60. recorder.add("remember feature flags", async () => {
  61. try {
  62. ffs = {
  63. ...ffs,
  64. ...step.args[1],
  65. };
  66. } catch (err) {
  67. console.error(err);
  68. }
  69. });
  70. }
  71. if (hasStepName("setFeatureFlagsDefaultValue", step)) {
  72. recorder.add("remember feature flags default value", async () => {
  73. try {
  74. defaultValue = step.args[1];
  75. } catch (err) {
  76. console.error(err);
  77. }
  78. });
  79. }
  80. });
  81. };