How to use getSteps method in Cucumber-gherkin

Best JavaScript code snippet using cucumber-gherkin

mstepper.js

Source:mstepper.js Github

copy

Full Screen

...39          classes = _this.classes,40          _methodsBindingManager = _this._methodsBindingManager,41          _openAction = _this._openAction; // Calls the _formWrapperManager42      _this.form = _formWrapperManager(); // Opens the first step (or other specified in the constructor)43      _openAction(getSteps().steps[options.firstActive], undefined, undefined, true); // Gathers the steps and send them to the methodsBinder44      _methodsBindingManager(stepper.querySelectorAll(".".concat(classes.STEP)));45    });46    _defineProperty(this, "_methodsBindingManager", function (steps) {47      var unbind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;48      var classes = _this.classes,49          _formSubmitHandler = _this._formSubmitHandler,50          _nextStepProxy = _this._nextStepProxy,51          _prevStepProxy = _this._prevStepProxy,52          _stepTitleClickHandler = _this._stepTitleClickHandler,53          form = _this.form,54          options = _this.options;55      var addMultipleEventListeners = MStepper.addMultipleEventListeners,56          removeMultipleEventListeners = MStepper.removeMultipleEventListeners,57          nodesIterator = MStepper.nodesIterator,58          tabbingDisabler = MStepper.tabbingDisabler;59      var bindOrUnbind = unbind ? removeMultipleEventListeners : addMultipleEventListeners; // Sets the binding function60      var bindEvents = function bindEvents(step) {61        var nextBtns = step.getElementsByClassName(classes.NEXTSTEPBTN);62        var prevBtns = step.getElementsByClassName(classes.PREVSTEPBTN);63        var stepsTitle = step.getElementsByClassName(classes.STEPTITLE);64        var inputs = step.querySelectorAll('input, select, textarea, button');65        var submitButtons = step.querySelectorAll('button[type="submit"]');66        bindOrUnbind(nextBtns, 'click', _nextStepProxy, false);67        bindOrUnbind(prevBtns, 'click', _prevStepProxy, false);68        bindOrUnbind(stepsTitle, 'click', _stepTitleClickHandler); // Prevents the tabbing issue (https://github.com/Kinark/Materialize-stepper/issues/49)69        if (inputs.length) bindOrUnbind(inputs[inputs.length - 1], 'keydown', tabbingDisabler); // Binds to the submit button an internal handler to manage validation70        if (submitButtons && form && options.validationFunction) bindOrUnbind(submitButtons, 'keydown', _formSubmitHandler);71        return step;72      }; // Calls the binder function in the right way (if it's a unique step or multiple ones)73      if (steps instanceof Element) bindEvents(steps);else nodesIterator(steps, function (step) {74        return bindEvents(step);75      });76    });77    _defineProperty(this, "_formSubmitHandler", function (e) {78      if (!_this._validationFunctionCaller()) e.preventDefault();79    });80    _defineProperty(this, "resetStepper", function () {81      if (_this.form) {82        _this.form.reset();83        _this.openStep(_this.options.firstActive);84      }85    });86    _defineProperty(this, "_openAction", function (step, cb) {87      var closeActiveStep = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;88      var skipAutoFocus = arguments.length > 3 ? arguments[3] : undefined;89      var _slideDown = _this._slideDown,90          classes = _this.classes,91          getSteps = _this.getSteps,92          _closeAction = _this._closeAction,93          stepper = _this.stepper,94          options = _this.options; // Gets the active step element95      var activeStep = getSteps().active.step; // If the active step is the same as the one that has been asked to be opened, returns the step96      if (activeStep && activeStep.isSameNode(step)) return step; // Gets the step content div inside the step97      var stepContent = step.getElementsByClassName(classes.STEPCONTENT)[0];98      step.classList.remove(classes.DONESTEP); // Checks if the step is currently horizontal or vertical99      if (window.innerWidth < 993 || !stepper.classList.contains(classes.HORIZONTALSTEPPER)) {100        // The stepper is running in vertical mode101        // Calls the slideDown private method if the stepper is vertical102        _slideDown(stepContent, classes.ACTIVESTEP, step, cb); // Beginning of disabled autoFocusInput function due to issues with scroll103        if (!skipAutoFocus) {104          _slideDown(stepContent, classes.ACTIVESTEP, step, function () {105            // Gets the inputs from the nextStep to focus on the first one (temporarily disabled)106            var nextStepInputs = stepContent.querySelector('input, select, textarea'); // Focus on the first input of the next step (temporarily disabled)107            if (options.autoFocusInput && nextStepInputs) nextStepInputs.focus();108            if (cb && typeof cb === 'function') cb();109          });110        } // Enf of disabled autoFocusInput function due to issues with scroll111      } else {112        // The stepper is running in horizontal mode113        // Adds the class 'active' from the step, since all the animation is made by the CSS114        step.classList.add('active');115      } // If it was requested to close the active step as well, does it (default=true)116      if (activeStep && closeActiveStep) _closeAction(activeStep);117      return step;118    });119    _defineProperty(this, "_closeAction", function (step, cb) {120      var _slideUp = _this._slideUp,121          classes = _this.classes,122          stepper = _this.stepper,123          _smartListenerUnbind = _this._smartListenerUnbind,124          _smartListenerBind = _this._smartListenerBind; // Gets the step content div inside the step125      var stepContent = step.getElementsByClassName(classes.STEPCONTENT)[0]; // Checks if the step is currently horizontal or vertical126      if (window.innerWidth < 993 || !stepper.classList.contains(classes.HORIZONTALSTEPPER)) {127        // The stepper is running in vertical mode128        // Calls the slideUp private method on the step129        _slideUp(stepContent, classes.ACTIVESTEP, step, cb);130      } else {131        // The stepper is running in horizontal mode132        // If there's a callback, handles it133        if (cb) {134          // Defines a function to be called after the transition's end135          var waitForTransitionToCb = function waitForTransitionToCb(e) {136            // If the transition is not 'left', returns137            if (e.propertyName !== 'left') return; // Unbinds the listener from the element138            _smartListenerUnbind(stepContent, 'transitionend', waitForTransitionToCb); // Calls the callback139            cb();140          }; // Binds the callback caller function to the event 'transitionend'141          _smartListenerBind(stepContent, 'transitionend', waitForTransitionToCb);142        } // Removes the class 'active' from the step, since all the animation is made by the CSS143        step.classList.remove('active');144      }145      return step;146    });147    _defineProperty(this, "_nextStepProxy", function (e) {148      return _this.nextStep(undefined, undefined, e);149    });150    _defineProperty(this, "_prevStepProxy", function (e) {151      return _this.prevStep(undefined, e);152    });153    _defineProperty(this, "_stepTitleClickHandler", function (e) {154      var getSteps = _this.getSteps,155          classes = _this.classes,156          nextStep = _this.nextStep,157          prevStep = _this.prevStep,158          stepper = _this.stepper,159          _openAction = _this._openAction;160      var _getSteps = getSteps(),161          steps = _getSteps.steps,162          active = _getSteps.active;163      var clickedStep = e.target.closest(".".concat(classes.STEP)); // Checks if the stepper is linear or not164      if (stepper.classList.contains(classes.LINEAR)) {165        // Linear stepper detected166        // Get the index of the active step167        var clickedStepIndex = Array.prototype.indexOf.call(steps, clickedStep); // If the step clicked is the next one, calls nextStep(), if it's the previous one, calls prevStep(), otherwise do nothing168        if (clickedStepIndex == active.index + 1) nextStep();else if (clickedStepIndex == active.index - 1) prevStep();169      } else {170        // Non-linear stepper detected171        // Opens the step clicked172        _openAction(clickedStep);173      }174    });175    _defineProperty(this, "nextStep", function (cb, skipFeedback, e) {176      if (e && e.preventDefault) e.preventDefault();177      var options = _this.options,178          getSteps = _this.getSteps,179          activateFeedback = _this.activateFeedback,180          form = _this.form,181          wrongStep = _this.wrongStep,182          classes = _this.classes,183          _openAction = _this._openAction,184          stepper = _this.stepper,185          events = _this.events,186          destroyFeedback = _this.destroyFeedback,187          _validationFunctionCaller = _this._validationFunctionCaller;188      var showFeedbackPreloader = options.showFeedbackPreloader,189          validationFunction = options.validationFunction;190      var _getSteps2 = getSteps(),191          active = _getSteps2.active;192      var nextStep = getSteps().steps[active.index + 1]; // Gets the feedback function (if any) from the button193      var feedbackFunction = e && e.target ? e.target.dataset.feedback : null; // Checks if there's a validation function defined194      if (validationFunction && !_validationFunctionCaller()) {195        // There's a validation function and no feedback function196        // The validation function was already called in the if statement and it retuerned false, so returns the calling of the wrongStep method197        return wrongStep();198      } // Checks if there's a feedback function199      if (feedbackFunction && !skipFeedback) {200        // There's a feedback function and it wasn't requested to skip it201        // If showFeedbackPreloader is true (default=true), activates it202        if (showFeedbackPreloader && !active.step.dataset.nopreloader) activateFeedback(); // Calls the feedbackFunction203        window[feedbackFunction](destroyFeedback, form, active.step.querySelector(".".concat(classes.STEPCONTENT))); // Returns to prevent the nextStep method from being called204        return;205      } // Adds the class 'done' to the current step206      active.step.classList.add(classes.DONESTEP); // Opens the next one207      _openAction(nextStep, cb); // Dispatches the events208      stepper.dispatchEvent(events.STEPCHANGE);209      stepper.dispatchEvent(events.NEXTSTEP);210    });211    _defineProperty(this, "prevStep", function (cb, e) {212      if (e && e.preventDefault) e.preventDefault();213      var getSteps = _this.getSteps,214          _openAction = _this._openAction,215          stepper = _this.stepper,216          events = _this.events,217          destroyFeedback = _this.destroyFeedback;218      var activeStep = getSteps().active;219      var prevStep = getSteps().steps[activeStep.index + -1]; // Destroyes the feedback preloader, if any220      destroyFeedback(); // Opens the previous step221      _openAction(prevStep, cb); // Dispatches the events222      stepper.dispatchEvent(events.STEPCHANGE);223      stepper.dispatchEvent(events.PREVSTEP);224    });225    _defineProperty(this, "openStep", function (index, cb) {226      var getSteps = _this.getSteps,227          _openAction = _this._openAction,228          stepper = _this.stepper,229          events = _this.events,230          destroyFeedback = _this.destroyFeedback;231      var stepToOpen = getSteps().steps[index]; // Destroyes the feedback preloader, if any232      destroyFeedback(); // Opens the requested step233      _openAction(stepToOpen, cb); // Dispatches the events234      stepper.dispatchEvent(events.STEPCHANGE);235    });236    _defineProperty(this, "wrongStep", function () {237      var getSteps = _this.getSteps,238          classes = _this.classes,239          stepper = _this.stepper,240          events = _this.events; // Add the WRONGSTEP class to the step241      getSteps().active.step.classList.add(classes.WRONGSTEP); // Gets all the inputs from the active step242      var inputs = getSteps().active.step.querySelectorAll('input, select, textarea'); // Defines a function to be binded to any change in any input243      var removeWrongOnInput = function removeWrongOnInput() {244        // If there's a change, removes the WRONGSTEP class245        getSteps().active.step.classList.remove(classes.WRONGSTEP); // Unbinds the listener from the element246        MStepper.removeMultipleEventListeners(inputs, 'input', removeWrongOnInput);247      }; // Binds the removeWrongOnInput function to the inputs, listening to the event 'input'248      MStepper.addMultipleEventListeners(inputs, 'input', removeWrongOnInput); // Dispatches the event249      stepper.dispatchEvent(events.STEPERROR);250    });251    _defineProperty(this, "activateFeedback", function () {252      var getSteps = _this.getSteps,253          classes = _this.classes,254          options = _this.options,255          stepper = _this.stepper,256          events = _this.events;257      var activeStep = getSteps().active.step; // Adds the FEEDBACKINGSTEP class to the step258      activeStep.classList.add(classes.FEEDBACKINGSTEP); // Gets the step content div inside the step259      var content = activeStep.getElementsByClassName(classes.STEPCONTENT)[0]; // Inserts the predefined prealoder in the step content div260      content.insertAdjacentHTML('afterBegin', "<div class=\"".concat(classes.PRELOADERWRAPPER, "\">").concat(options.feedbackPreloader, "</div>")); // Dispatches the event261      stepper.dispatchEvent(events.FEEDBACKING);262    });263    _defineProperty(this, "destroyFeedback", function (triggerNextStep) {264      var getSteps = _this.getSteps,265          classes = _this.classes,266          nextStep = _this.nextStep,267          stepper = _this.stepper,268          events = _this.events;269      var activeStep = getSteps().active.step; // If there's no activeStep or preloader, returns270      if (!activeStep || !activeStep.classList.contains(classes.FEEDBACKINGSTEP)) return; // Removes the FEEDBACKINGSTEP class from the step271      activeStep.classList.remove(classes.FEEDBACKINGSTEP); // Gets the preloader div272      var fbDiv = activeStep.getElementsByClassName(classes.PRELOADERWRAPPER)[0]; // Removes the preloader div273      fbDiv.parentNode.removeChild(fbDiv); // Calls nextStep if requested (default=false)274      if (triggerNextStep) nextStep(undefined, true); // Dispatches the event275      stepper.dispatchEvent(events.FEEDBACKDESTROYED);276    });277    _defineProperty(this, "getSteps", function () {278      var stepper = _this.stepper,279          classes = _this.classes;280      var steps = stepper.querySelectorAll("li.".concat(classes.STEP));281      var activeStep = stepper.querySelector("li.".concat(classes.ACTIVESTEP));282      var activeStepIndex = Array.prototype.indexOf.call(steps, activeStep);283      return {284        steps: steps,285        active: {286          step: activeStep,287          index: activeStepIndex288        }289      };290    });291    _defineProperty(this, "activateStep", function (elements, index) {292      var getSteps = _this.getSteps,293          _slideDown = _this._slideDown,294          stepper = _this.stepper,295          _methodsBindingManager = _this._methodsBindingManager;296      var nodesIterator = MStepper.nodesIterator;297      var currentSteps = getSteps();298      var nextStep = currentSteps.steps[index]; // Stores a let variable to return the right element after the activation299      var returnableElement = null; // Starts the checking of the elements parameter300      if (typeof elements === 'string') {301        // The element is in string format302        // Insert it with the insertAdjacentHTML function303        nextStep.insertAdjacentHTML('beforeBegin', elements); // Defines the inserted element as the returnableElement304        returnableElement = nextStep.previousSibling; // Activates (slideDown) the step305        _slideDown(returnableElement);306      } else if (Array.isArray(elements)) {307        // The element is in array format, probably an array of strings308        // Sets the returnableElement to be an empty array309        returnableElement = []; // Loops through the array310        elements.forEach(function (element) {311          // Inserts each element with the insertAdjacentHTML function312          nextStep.insertAdjacentHTML('beforeBegin', element); // Adds each element to the returnableElement array313          returnableElement.push(nextStep.previousSibling); // Activates (slideDown) each element314          _slideDown(nextStep.previousSibling);315        });316      } else if (elements instanceof Element || elements instanceof HTMLCollection || elements instanceof NodeList) {317        // The element is an HTMLElement or an HTMLCollection318        // Insert it/them with the insertBefore function and sets the returnableElement319        returnableElement = stepper.insertBefore(elements, nextStep); // If it's and HTMLElement, activates (slideDown) it, if it's an HTMLCollection, activates (slideDown) each of them320        if (elements instanceof Element) _slideDown(returnableElement);else nodesIterator(returnableElement, function (appendedElement) {321          return _slideDown(appendedElement);322        });323      } // Do the bidings to the new step(s)324      if (returnableElement) _methodsBindingManager(returnableElement); // Returns the added/activated elements325      return returnableElement;326    });327    _defineProperty(this, "deactivateStep", function (elements) {328      var _slideUp = _this._slideUp,329          stepper = _this.stepper,330          _methodsBindingManager = _this._methodsBindingManager;331      var nodesIterator = MStepper.nodesIterator; // Sets a function to group the orders to deactivate and remove the steps332      var doIt = function doIt(element) {333        // Checks if the step really exists in the stepper334        if (stepper.contains(elements)) {335          // Yeah, it does exist336          // Unbinds the listeners previously binded to the step337          _methodsBindingManager(element, true); // Slides up and removes afterwards338          _slideUp(element, undefined, undefined, function () {339            return stepper.removeChild(element);340          });341        }342      }; // Checks if the elements is an HTMLElement or an HTMLCollection and calls the function doIt in the right way343      if (elements instanceof Element) doIt(elements);else if (elements instanceof HTMLCollection || elements instanceof NodeList) nodesIterator(elements, function (element) {344        return doIt(element);345      }); // Returns the step(s), in case you want to activate it/them again.346      return elements;347    });348    _defineProperty(this, "_slideDown", function (element, className) {349      var classElement = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : element;350      var cb = arguments.length > 3 ? arguments[3] : undefined;351      // Gets the height of the element when it's already visible352      var height = "".concat(MStepper.getUnknownHeight(element), "px"); // Defines a function to be called after the transition's end353      var endSlideDown = function endSlideDown(e) {354        // If the transition is not 'height', returns355        if (e.propertyName !== 'height') return; // Unbinds the listener from the element356        _this._smartListenerUnbind(element, 'transitionend', endSlideDown); // Removes properties needed for the transition to occur357        MStepper.removeMultipleProperties(element, 'visibility overflow height display'); // Calls the callback() if any358        if (cb) cb();359      }; // Calls an animation frame to avoid async weird stuff360      requestAnimationFrame(function () {361        // Prepare the element for animation362        element.style.overflow = 'hidden';363        element.style.paddingBottom = '0';364        element.style.height = '0';365        element.style.visibility = 'unset';366        element.style.display = 'block'; // Calls another animation frame to wait for the previous changes to take effect367        requestAnimationFrame(function () {368          // Binds the "conclusion" function to the event 'transitionend'369          _this._smartListenerBind(element, 'transitionend', endSlideDown); // Sets the final height to the element to trigger the transition370          element.style.height = height; // Removes the 'padding-bottom: 0' setted previously to trigger it too371          element.style.removeProperty('padding-bottom'); // If a className for the slided element is required, add it372          if (className) classElement.classList.add(className);373        });374      }); // Returns the original element to enable chain functions375      return element;376    });377    _defineProperty(this, "_slideUp", function (element, className) {378      var classElement = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : element;379      var cb = arguments.length > 3 ? arguments[3] : undefined;380      // Gets the element's height381      var height = "".concat(element.offsetHeight, "px"); // Defines a function to be called after the transition's end382      var endSlideUp = function endSlideUp(e) {383        // If the transition is not 'height', returns384        if (e.propertyName !== 'height') return; // Unbinds the listener from the element385        _this._smartListenerUnbind(element, 'transitionend', endSlideUp); // Sets display none for the slided element386        element.style.display = 'none'; // Removes properties needed for the transition to occur387        MStepper.removeMultipleProperties(element, 'visibility overflow height padding-bottom'); // Calls the callback() if any388        if (cb) cb();389      }; // Calls an animation frame to avoid async weird stuff390      requestAnimationFrame(function () {391        // Prepare the element for animation392        element.style.overflow = 'hidden';393        element.style.visibility = 'unset';394        element.style.display = 'block';395        element.style.height = height; // Calls another animation frame to wait for the previous changes to take effect396        requestAnimationFrame(function () {397          // Binds the "conclusion" function to the event 'transitionend'398          _this._smartListenerBind(element, 'transitionend', endSlideUp); // Sets the height to 0 the element to trigger the transition399          element.style.height = '0'; // Sets the 'padding-bottom: 0' to transition the padding400          element.style.paddingBottom = '0'; // If a removal of a className for the slided element is required, remove it401          if (className) classElement.classList.remove(className);402        });403      }); // Returns the original element to enable chain functions404      return element;405    });406    _defineProperty(this, "_formWrapperManager", function () {407      var stepper = _this.stepper,408          options = _this.options; // Checks if there's a form wrapping the stepper and gets it409      var form = stepper.closest('form'); // Checks if the form doesn't exist and the autoFormCreation option is true (default=true)410      if (!form && options.autoFormCreation) {411        // The form doesn't exist and the autoFormCreation is true412        // Gathers the form settings from the dataset of the stepper413        var dataAttrs = stepper.dataset || {};414        var method = dataAttrs.method || 'GET';415        var action = dataAttrs.action || '?'; // Creates a form element416        var wrapper = document.createElement('form'); // Defines the form's settings417        wrapper.method = method;418        wrapper.action = action; // Wraps the stepper with it419        stepper.parentNode.insertBefore(wrapper, stepper);420        wrapper.appendChild(stepper); // Returns the wrapper (the form)421        return wrapper;422      } else if (form.length) {423        // The form exists424        // Returns the form425        return form;426      } else {427        // The form doesn't exist autoFormCreation is false428        // Returns null429        return null;430      }431    });432    _defineProperty(this, "_validationFunctionCaller", function () {433      var options = _this.options,434          getSteps = _this.getSteps,435          form = _this.form,436          classes = _this.classes;437      return options.validationFunction(form, getSteps().active.step.querySelector(".".concat(classes.STEPCONTENT)));438    });439    _defineProperty(this, "_smartListenerBind", function (el, event, fn) {440      var similar = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;441      var callFn = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false;442      var listenerStore = _this.listenerStore; // Builds an object with the element, event and function.443      var newListener = {444        el: el,445        event: event,446        fn: fn447      }; // Checks if similar listeners will be unbinded before the binding448      if (similar) {449        // Loops through the store searching for functions binded to the same element listening for the same event450        for (var i = 0; i < listenerStore.length; i++) {451          var listener = listenerStore[i]; // Unbind if found...

Full Screen

Full Screen

functional.js

Source:functional.js Github

copy

Full Screen

...62        dataFlowSchema,63        foldStepResults,64        frontController,65        getConditions,66        getSteps: ({ stepResults }) => getSteps(Object.assign({ stepResults }, spies))67      });68      const approximateDeliveryTime = await orderPizza(input);69      expect(spies.addProfileToDb.notCalled).to.equal(true);70      expect(spies.fetchAddressForPostcode.calledWith({ postcode: input.address.postcode })).to.equal(true);71      expect(spies.sendOrderConfirmationEmail.calledWith({72        body: getOrderConfirmationEmailBody({ approximateDeliveryTime: defaultApproximateDeliveryTime }),73        email: input.email,74        subject: getOrderConfirmationEmailSubject()75      })).to.equal(true);76      expect(spies.sendWelcomeEmail.notCalled).to.equal(true);77      expect(spies.submitOrderToRestaurant.calledWith({78        address: verifiedAddress,79        email: input.email,80        items: input.orderedItems81      })).to.equal(true);82      expect(approximateDeliveryTime).to.equal(defaultApproximateDeliveryTime);83    });84    it('approximateDeliveryTime given by restaurant', async () => {85      const restaurantApproximateDeliveryTime = '45 minutes';86      const verifiedAddress = Object.assign({}, input.address, {87        hasItBeenVerified: true,88        line2: input.address.line2,89        line3: input.address.line390      });91      const spies = {92        addProfileToDb: sinon.spy(),93        fetchAddressForPostcode: sinon.stub().returns(input.address),94        sendOrderConfirmationEmail: sinon.spy(),95        sendWelcomeEmail: sinon.spy(),96        submitOrderToRestaurant: sinon.stub().returns({ approximateDeliveryTime: restaurantApproximateDeliveryTime })97      };98      const orderPizza = createAction({99        dataFlowSchema,100        foldStepResults,101        frontController,102        getConditions,103        getSteps: ({ stepResults }) => getSteps(Object.assign({ stepResults }, spies))104      });105      const approximateDeliveryTime = await orderPizza(input);106      expect(spies.addProfileToDb.notCalled).to.equal(true);107      expect(spies.fetchAddressForPostcode.calledWith({ postcode: input.address.postcode })).to.equal(true);108      expect(spies.sendOrderConfirmationEmail.calledWith({109        body: getOrderConfirmationEmailBody({ approximateDeliveryTime: restaurantApproximateDeliveryTime }),110        email: input.email,111        subject: getOrderConfirmationEmailSubject()112      })).to.equal(true);113      expect(spies.sendWelcomeEmail.notCalled).to.equal(true);114      expect(spies.submitOrderToRestaurant.calledWith({115        address: verifiedAddress,116        email: input.email,117        items: input.orderedItems118      })).to.equal(true);119      expect(approximateDeliveryTime).to.equal(restaurantApproximateDeliveryTime);120    });121    it('fetchAddressForPostcode() returns null', async () => {122      const spies = {123        addProfileToDb: sinon.spy(),124        fetchAddressForPostcode: sinon.stub().returns(null),125        sendOrderConfirmationEmail: sinon.spy(),126        sendWelcomeEmail: sinon.spy(),127        submitOrderToRestaurant: sinon.stub().returns({ approximateDeliveryTime: defaultApproximateDeliveryTime })128      };129      const verifiedAddress = Object.assign({}, input.address, {130        hasItBeenVerified: false,131        line2: input.address.line2,132        line3: input.address.line3133      });134      const orderPizza = createAction({135        dataFlowSchema,136        foldStepResults,137        frontController,138        getConditions,139        getSteps: ({ stepResults }) => getSteps(Object.assign({ stepResults }, spies))140      });141      const approximateDeliveryTime = await orderPizza(input);142      expect(spies.addProfileToDb.notCalled).to.equal(true);143      expect(spies.fetchAddressForPostcode.calledWith({ postcode: input.address.postcode })).to.equal(true);144      expect(spies.sendOrderConfirmationEmail.calledWith({145        body: getOrderConfirmationEmailBody({ approximateDeliveryTime: defaultApproximateDeliveryTime }),146        email: input.email,147        subject: getOrderConfirmationEmailSubject()148      })).to.equal(true);149      expect(spies.sendWelcomeEmail.notCalled).to.equal(true);150      expect(spies.submitOrderToRestaurant.calledWith({151        address: verifiedAddress,152        email: input.email,153        items: input.orderedItems154      })).to.equal(true);155      expect(approximateDeliveryTime).to.equal(defaultApproximateDeliveryTime);156    });157    it('fetchAddressForPostcode() rejects with an error', async () => {158      const spies = {159        addProfileToDb: sinon.spy(),160        fetchAddressForPostcode: sinon.stub().rejects(new Error()),161        sendOrderConfirmationEmail: sinon.spy(),162        sendWelcomeEmail: sinon.spy(),163        submitOrderToRestaurant: sinon.stub().returns({ approximateDeliveryTime: defaultApproximateDeliveryTime })164      };165      const verifiedAddress = Object.assign({}, input.address, {166        hasItBeenVerified: false,167        line2: input.address.line2,168        line3: input.address.line3169      });170      const orderPizza = createAction({171        dataFlowSchema,172        foldStepResults,173        frontController,174        getConditions,175        getSteps: ({ stepResults }) => getSteps(Object.assign({ stepResults }, spies))176      });177      const approximateDeliveryTime = await orderPizza(input);178      expect(spies.addProfileToDb.notCalled).to.equal(true);179      expect(spies.fetchAddressForPostcode.calledWith({ postcode: input.address.postcode })).to.equal(true);180      expect(spies.sendOrderConfirmationEmail.calledWith({181        body: getOrderConfirmationEmailBody({ approximateDeliveryTime: defaultApproximateDeliveryTime }),182        email: input.email,183        subject: getOrderConfirmationEmailSubject()184      })).to.equal(true);185      expect(spies.sendWelcomeEmail.notCalled).to.equal(true);186      expect(spies.submitOrderToRestaurant.calledWith({187        address: verifiedAddress,188        email: input.email,189        items: input.orderedItems190      })).to.equal(true);191      expect(approximateDeliveryTime).to.equal(defaultApproximateDeliveryTime);192    });193    it('sendOrderConfirmationEmail() rejects with an error', async () => {194      const spies = {195        addProfileToDb: sinon.spy(),196        fetchAddressForPostcode: sinon.stub().returns(input.address),197        sendOrderConfirmationEmail: sinon.stub().rejects(new Error()),198        sendWelcomeEmail: sinon.spy(),199        submitOrderToRestaurant: sinon.stub().returns({ approximateDeliveryTime: defaultApproximateDeliveryTime })200      };201      const verifiedAddress = Object.assign({}, input.address, {202        hasItBeenVerified: true,203        line2: input.address.line2,204        line3: input.address.line3205      });206      const orderPizza = createAction({207        dataFlowSchema,208        foldStepResults,209        frontController,210        getConditions,211        getSteps: ({ stepResults }) => getSteps(Object.assign({ stepResults }, spies))212      });213      const approximateDeliveryTime = await orderPizza(input);214      expect(spies.addProfileToDb.notCalled).to.equal(true);215      expect(spies.fetchAddressForPostcode.calledWith({ postcode: input.address.postcode })).to.equal(true);216      expect(spies.sendOrderConfirmationEmail.calledWith({217        body: getOrderConfirmationEmailBody({ approximateDeliveryTime: defaultApproximateDeliveryTime }),218        email: input.email,219        subject: getOrderConfirmationEmailSubject()220      })).to.equal(true);221      expect(spies.sendWelcomeEmail.notCalled).to.equal(true);222      expect(spies.submitOrderToRestaurant.calledWith({223        address: verifiedAddress,224        email: input.email,225        items: input.orderedItems226      })).to.equal(true);227      expect(approximateDeliveryTime).to.equal(defaultApproximateDeliveryTime);228    });229    it('sendWelcomeEmail() rejects with an error', async () => {230      const spies = {231        addProfileToDb: sinon.spy(),232        fetchAddressForPostcode: sinon.stub().returns(input.address),233        sendOrderConfirmationEmail: sinon.spy(),234        sendWelcomeEmail: sinon.stub().rejects(new Error()),235        submitOrderToRestaurant: sinon.stub().returns({ approximateDeliveryTime: defaultApproximateDeliveryTime })236      };237      const verifiedAddress = Object.assign({}, input.address, {238        hasItBeenVerified: true,239        line2: input.address.line2,240        line3: input.address.line3241      });242      const orderPizza = createAction({243        dataFlowSchema,244        foldStepResults,245        frontController,246        getConditions,247        getSteps: ({ stepResults }) => getSteps(Object.assign({ stepResults }, spies))248      });249      const approximateDeliveryTime = await orderPizza(input);250      expect(spies.addProfileToDb.notCalled).to.equal(true);251      expect(spies.fetchAddressForPostcode.calledWith({ postcode: input.address.postcode })).to.equal(true);252      expect(spies.sendOrderConfirmationEmail.calledWith({253        body: getOrderConfirmationEmailBody({ approximateDeliveryTime: defaultApproximateDeliveryTime }),254        email: input.email,255        subject: getOrderConfirmationEmailSubject()256      })).to.equal(true);257      expect(spies.sendWelcomeEmail.notCalled).to.equal(true);258      expect(spies.submitOrderToRestaurant.calledWith({259        address: verifiedAddress,260        email: input.email,261        items: input.orderedItems262      })).to.equal(true);263      expect(approximateDeliveryTime).to.equal(defaultApproximateDeliveryTime);264    });265  });266  describe('submit order and create a customer profile', () => {267    let input;268    before(() => {269      input = {270        address: {271          line1: 'Buckingham Palace',272          postcode: 'SW1A 1AA',273          town: 'London'274        },275        email: 'hello@glue.codes',276        firstName: 'Krzys',277        lastName: 'Czopp',278        orderedItems: [279          {280            id: 'somePizzaId',281            quantity: 1282          },283          {284            id: 'someSideId',285            quantity: 2286          }287        ],288        password: 'somePassword'289      };290    });291    it('no approximateDeliveryTime returned from restaurant', async () => {292      const verifiedAddress = Object.assign({}, input.address, {293        hasItBeenVerified: true,294        line2: input.address.line2,295        line3: input.address.line3296      });297      const spies = {298        addProfileToDb: sinon.spy(),299        fetchAddressForPostcode: sinon.stub().returns(input.address),300        sendOrderConfirmationEmail: sinon.spy(),301        sendWelcomeEmail: sinon.spy(),302        submitOrderToRestaurant: sinon.stub().returns({ approximateDeliveryTime: null })303      };304      const orderPizza = createAction({305        dataFlowSchema,306        foldStepResults,307        frontController,308        getConditions,309        getSteps: ({ stepResults }) => getSteps(Object.assign({ stepResults }, spies))310      });311      const approximateDeliveryTime = await orderPizza(input);312      expect(spies.addProfileToDb.calledWith({313        address: verifiedAddress,314        email: input.email,315        firstName: input.firstName,316        lastName: input.lastName,317        password: input.password318      })).to.equal(true);319      expect(spies.fetchAddressForPostcode.calledWith({ postcode: input.address.postcode })).to.equal(true);320      expect(spies.sendOrderConfirmationEmail.calledWith({321        body: getOrderConfirmationEmailBody({ approximateDeliveryTime: defaultApproximateDeliveryTime }),322        email: input.email,323        subject: getOrderConfirmationEmailSubject()324      })).to.equal(true);325      expect(spies.sendWelcomeEmail.calledWith({326        body: getWelcomeEmailBody({ firstName: input.firstName }),327        email: input.email,328        subject: getWelcomeEmailSubject()329      })).to.equal(true);330      expect(spies.submitOrderToRestaurant.calledWith({331        address: verifiedAddress,332        email: input.email,333        items: input.orderedItems334      })).to.equal(true);335      expect(approximateDeliveryTime).to.equal(defaultApproximateDeliveryTime);336    });337    it('approximateDeliveryTime given by restaurant', async () => {338      const restaurantApproximateDeliveryTime = '45 minutes';339      const verifiedAddress = Object.assign({}, input.address, {340        hasItBeenVerified: true,341        line2: input.address.line2,342        line3: input.address.line3343      });344      const spies = {345        addProfileToDb: sinon.spy(),346        fetchAddressForPostcode: sinon.stub().returns(input.address),347        sendOrderConfirmationEmail: sinon.spy(),348        sendWelcomeEmail: sinon.spy(),349        submitOrderToRestaurant: sinon.stub().returns({ approximateDeliveryTime: restaurantApproximateDeliveryTime })350      };351      const orderPizza = createAction({352        dataFlowSchema,353        foldStepResults,354        frontController,355        getConditions,356        getSteps: ({ stepResults }) => getSteps(Object.assign({ stepResults }, spies))357      });358      const approximateDeliveryTime = await orderPizza(input);359      expect(spies.addProfileToDb.calledWith({360        address: verifiedAddress,361        email: input.email,362        firstName: input.firstName,363        lastName: input.lastName,364        password: input.password365      })).to.equal(true);366      expect(spies.fetchAddressForPostcode.calledWith({ postcode: input.address.postcode })).to.equal(true);367      expect(spies.sendOrderConfirmationEmail.calledWith({368        body: getOrderConfirmationEmailBody({ approximateDeliveryTime: restaurantApproximateDeliveryTime }),369        email: input.email,370        subject: getOrderConfirmationEmailSubject()371      })).to.equal(true);372      expect(spies.sendWelcomeEmail.calledWith({373        body: getWelcomeEmailBody({ firstName: input.firstName }),374        email: input.email,375        subject: getWelcomeEmailSubject()376      })).to.equal(true);377      expect(spies.submitOrderToRestaurant.calledWith({378        address: verifiedAddress,379        email: input.email,380        items: input.orderedItems381      })).to.equal(true);382      expect(approximateDeliveryTime).to.equal(restaurantApproximateDeliveryTime);383    });384    it('fetchAddressForPostcode() returns null', async () => {385      const spies = {386        addProfileToDb: sinon.spy(),387        fetchAddressForPostcode: sinon.stub().returns(null),388        sendOrderConfirmationEmail: sinon.spy(),389        sendWelcomeEmail: sinon.spy(),390        submitOrderToRestaurant: sinon.stub().returns({ approximateDeliveryTime: defaultApproximateDeliveryTime })391      };392      const verifiedAddress = Object.assign({}, input.address, {393        hasItBeenVerified: false,394        line2: input.address.line2,395        line3: input.address.line3396      });397      const orderPizza = createAction({398        dataFlowSchema,399        foldStepResults,400        frontController,401        getConditions,402        getSteps: ({ stepResults }) => getSteps(Object.assign({ stepResults }, spies))403      });404      const approximateDeliveryTime = await orderPizza(input);405      expect(spies.addProfileToDb.calledWith({406        address: verifiedAddress,407        email: input.email,408        firstName: input.firstName,409        lastName: input.lastName,410        password: input.password411      })).to.equal(true);412      expect(spies.fetchAddressForPostcode.calledWith({ postcode: input.address.postcode })).to.equal(true);413      expect(spies.sendOrderConfirmationEmail.calledWith({414        body: getOrderConfirmationEmailBody({ approximateDeliveryTime: defaultApproximateDeliveryTime }),415        email: input.email,416        subject: getOrderConfirmationEmailSubject()417      })).to.equal(true);418      expect(spies.sendWelcomeEmail.calledWith({419        body: getWelcomeEmailBody({ firstName: input.firstName }),420        email: input.email,421        subject: getWelcomeEmailSubject()422      })).to.equal(true);423      expect(spies.submitOrderToRestaurant.calledWith({424        address: verifiedAddress,425        email: input.email,426        items: input.orderedItems427      })).to.equal(true);428      expect(approximateDeliveryTime).to.equal(defaultApproximateDeliveryTime);429    });430    it('fetchAddressForPostcode() rejects with an error', async () => {431      const spies = {432        addProfileToDb: sinon.spy(),433        fetchAddressForPostcode: sinon.stub().rejects(new Error()),434        sendOrderConfirmationEmail: sinon.spy(),435        sendWelcomeEmail: sinon.spy(),436        submitOrderToRestaurant: sinon.stub().returns({ approximateDeliveryTime: defaultApproximateDeliveryTime })437      };438      const verifiedAddress = Object.assign({}, input.address, {439        hasItBeenVerified: false,440        line2: input.address.line2,441        line3: input.address.line3442      });443      const orderPizza = createAction({444        dataFlowSchema,445        foldStepResults,446        frontController,447        getConditions,448        getSteps: ({ stepResults }) => getSteps(Object.assign({ stepResults }, spies))449      });450      const approximateDeliveryTime = await orderPizza(input);451      expect(spies.addProfileToDb.calledWith({452        address: verifiedAddress,453        email: input.email,454        firstName: input.firstName,455        lastName: input.lastName,456        password: input.password457      })).to.equal(true);458      expect(spies.fetchAddressForPostcode.calledWith({ postcode: input.address.postcode })).to.equal(true);459      expect(spies.sendOrderConfirmationEmail.calledWith({460        body: getOrderConfirmationEmailBody({ approximateDeliveryTime: defaultApproximateDeliveryTime }),461        email: input.email,462        subject: getOrderConfirmationEmailSubject()463      })).to.equal(true);464      expect(spies.sendWelcomeEmail.calledWith({465        body: getWelcomeEmailBody({ firstName: input.firstName }),466        email: input.email,467        subject: getWelcomeEmailSubject()468      })).to.equal(true);469      expect(spies.submitOrderToRestaurant.calledWith({470        address: verifiedAddress,471        email: input.email,472        items: input.orderedItems473      })).to.equal(true);474      expect(approximateDeliveryTime).to.equal(defaultApproximateDeliveryTime);475    });476    it('sendOrderConfirmationEmail() rejects with an error', async () => {477      const spies = {478        addProfileToDb: sinon.spy(),479        fetchAddressForPostcode: sinon.stub().returns(input.address),480        sendOrderConfirmationEmail: sinon.stub().rejects(new Error()),481        sendWelcomeEmail: sinon.spy(),482        submitOrderToRestaurant: sinon.stub().returns({ approximateDeliveryTime: defaultApproximateDeliveryTime })483      };484      const verifiedAddress = Object.assign({}, input.address, {485        hasItBeenVerified: true,486        line2: input.address.line2,487        line3: input.address.line3488      });489      const orderPizza = createAction({490        dataFlowSchema,491        foldStepResults,492        frontController,493        getConditions,494        getSteps: ({ stepResults }) => getSteps(Object.assign({ stepResults }, spies))495      });496      const approximateDeliveryTime = await orderPizza(input);497      expect(spies.addProfileToDb.calledWith({498        address: verifiedAddress,499        email: input.email,500        firstName: input.firstName,501        lastName: input.lastName,502        password: input.password503      })).to.equal(true);504      expect(spies.fetchAddressForPostcode.calledWith({ postcode: input.address.postcode })).to.equal(true);505      expect(spies.sendOrderConfirmationEmail.calledWith({506        body: getOrderConfirmationEmailBody({ approximateDeliveryTime: defaultApproximateDeliveryTime }),507        email: input.email,508        subject: getOrderConfirmationEmailSubject()509      })).to.equal(true);510      expect(spies.sendWelcomeEmail.calledWith({511        body: getWelcomeEmailBody({ firstName: input.firstName }),512        email: input.email,513        subject: getWelcomeEmailSubject()514      })).to.equal(true);515      expect(spies.submitOrderToRestaurant.calledWith({516        address: verifiedAddress,517        email: input.email,518        items: input.orderedItems519      })).to.equal(true);520      expect(approximateDeliveryTime).to.equal(defaultApproximateDeliveryTime);521    });522    it('sendWelcomeEmail() rejects with an error', async () => {523      const spies = {524        addProfileToDb: sinon.spy(),525        fetchAddressForPostcode: sinon.stub().returns(input.address),526        sendOrderConfirmationEmail: sinon.spy(),527        sendWelcomeEmail: sinon.stub().rejects(new Error()),528        submitOrderToRestaurant: sinon.stub().returns({ approximateDeliveryTime: defaultApproximateDeliveryTime })529      };530      const verifiedAddress = Object.assign({}, input.address, {531        hasItBeenVerified: true,532        line2: input.address.line2,533        line3: input.address.line3534      });535      const orderPizza = createAction({536        dataFlowSchema,537        foldStepResults,538        frontController,539        getConditions,540        getSteps: ({ stepResults }) => getSteps(Object.assign({ stepResults }, spies))541      });542      const approximateDeliveryTime = await orderPizza(input);543      expect(spies.addProfileToDb.calledWith({544        address: verifiedAddress,545        email: input.email,546        firstName: input.firstName,547        lastName: input.lastName,548        password: input.password549      })).to.equal(true);550      expect(spies.fetchAddressForPostcode.calledWith({ postcode: input.address.postcode })).to.equal(true);551      expect(spies.sendOrderConfirmationEmail.calledWith({552        body: getOrderConfirmationEmailBody({ approximateDeliveryTime: defaultApproximateDeliveryTime }),553        email: input.email,554        subject: getOrderConfirmationEmailSubject()...

Full Screen

Full Screen

TraversalHelper.js

Source:TraversalHelper.js Github

copy

Full Screen

...19 * TraversalHelper20 */21export default class TraversalHelper {22	//  public static boolean isLocalProperties(final Traversal.Admin<?, ?> traversal) {23	//  for (final Step step : traversal.getSteps()) {24	//  if (step instanceof RepeatStep) {25	//  for (final Traversal.Admin<?, ?> global : ((RepeatStep<?>) step).getGlobalChildren()) {26	//  if (TraversalHelper.hasStepOfAssignableClass(VertexStep.class, global))27	//  return false;28	// }29	// } else if (step instanceof VertexStep) {30	//  return false;31	// } else if (step instanceof EdgeVertexStep) {32	//  return false;33	// } else if (step instanceof TraversalParent) {34	//  for (final Traversal.Admin<?, ?> local : ((TraversalParent) step).getLocalChildren()) {35	//    if (!TraversalHelper.isLocalProperties(local))36	//      return false;37	//  }38	// }39	// }40	// return true;41	// }42	//43	// public static boolean isLocalStarGraph(final Traversal.Admin<?, ?> traversal) {44	//  return 'x' != isLocalStarGraph(traversal, 'v');45	// }46	//47	// private static char isLocalStarGraph(final Traversal.Admin<?, ?> traversal, char state) {48	//  if (state == 'u' &&49	//    (traversal instanceof ElementValueTraversal ||50	//    (traversal instanceof TokenTraversal && !((TokenTraversal) traversal).getToken().equals(T.id))))51	//  return 'x';52	//  for (final Step step : traversal.getSteps()) {53	//    if ((step instanceof PropertiesStep || step instanceof LabelStep || step instanceof PropertyMapStep) && state == 'u')54	//      return 'x';55	//    else if (step instanceof VertexStep) {56	//      if (state == 'u') return 'x';57	//      state = ((VertexStep) step).returnsVertex() ? 'u' : 'e';58	//    } else if (step instanceof EdgeVertexStep) {59	//      state = 'u';60	//    } else if (step instanceof HasContainerHolder && state == 'u') {61	//      for (final HasContainer hasContainer : ((HasContainerHolder) step).getHasContainers()) {62	//        if (!hasContainer.getKey().equals(T.id.getAccessor()))63	//          return 'x';64	//      }65	//    } else if (step instanceof TraversalParent) {66	//      final char currState = state;67	//      Set<Character> states = new HashSet<>();68	//      for (final Traversal.Admin<?, ?> local : ((TraversalParent) step).getLocalChildren()) {69	//        final char s = isLocalStarGraph(local, currState);70	//        if ('x' == s) return 'x';71	//        states.add(s);72	//      }73	//      if (!(step instanceof ByModulating)) {74	//        if (states.contains('u'))75	//          state = 'u';76	//        else if (states.contains('e'))77	//          state = 'e';78	//      }79	//      states.clear();80	//      for (final Traversal.Admin<?, ?> local : ((TraversalParent) step).getGlobalChildren()) {81	//        final char s = isLocalStarGraph(local, currState);82	//        if ('x' == s) return 'x';83	//        states.add(s);84	//      }85	//      if (states.contains('u'))86	//        state = 'u';87	//      else if (states.contains('e'))88	//        state = 'e';89	//      if (state != currState && (step instanceof RepeatStep || step instanceof MatchStep))90	//        return 'x';91	//    }92	//  }93	//  return state;94	// }95	/**96	 * Insert a step before a specified step instance.97	 *98	 * @param insertStep the step to insert99	 * @param afterStep  the step to insert the new step before100	 * @param traversal  the traversal on which the action should occur101	 */102	static insertBeforeStep(insertStep, afterStep, traversal) {103		traversal.addStep(insertStep, TraversalHelper.stepIndex(afterStep, traversal));104	}105	/**106	 * Insert a step after a specified step instance.107	 *108	 * @param insertStep the step to insert109	 * @param beforeStep the step to insert the new step after110	 * @param traversal  the traversal on which the action should occur111	 */112	static insertAfterStep(insertStep, beforeStep, traversal) {113		traversal.addStep(insertStep, TraversalHelper.stepIndex(beforeStep, traversal) + 1);114	}115	/**116	 * Replace a step with a new step.117	 *118	 * @param removeStep the step to remove119	 * @param insertStep the step to insert120	 * @param traversal  the traversal on which the action will occur121	 */122	static replaceStep(removeStep, insertStep, traversal) {123		traversal.addStep(insertStep, TraversalHelper.stepIndex(removeStep, traversal));124		traversal.removeStep(removeStep);125	}126	static insertTraversal(insertIndex, insertTraversal, traversal) {127		if (isNaN(insertIndex)) {128			const previousStep = insertIndex;129			return TraversalHelper.insertTraversal(TraversalHelper.stepIndex(previousStep, traversal), insertTraversal, traversal);130		}131		if (0 === traversal.getSteps().size()) {132			let currentStep = EmptyStep.instance();133			for (let i = 0; i < insertTraversal.getSteps().size(); i++) {134				const insertStep = insertTraversal.getSteps().getValue(i);135				currentStep = insertStep;136				traversal.addStep(insertStep);137			}138			return currentStep;139		} else {140			let currentStep = traversal.getSteps().getValue(insertIndex);141			for (let i = 0; i < insertTraversal.getSteps().size(); i++) {142				const insertStep = insertTraversal.getSteps().getValue(i);143				TraversalHelper.insertAfterStep(insertStep, currentStep, traversal);144				currentStep = insertStep;145			}146			return currentStep;147		}148	}149	static removeToTraversal(startStep, endStep, newTraversal) {150		const originalTraversal = startStep.getTraversal();151		let currentStep = startStep;152		while (currentStep !== endStep && !(currentStep instanceof EmptyStep)) {153			const temp = currentStep.getNextStep();154			originalTraversal.removeStep(currentStep);155			newTraversal.addStep(currentStep);156			currentStep = temp;157		}158	}159	/**160	 * Gets the index of a particular step in the {@link Traversal}.161	 *162	 * @param step      the step to retrieve the index for163	 * @param traversal the traversal to perform the action on164	 * @return the index of the step or -1 if the step is not present165	 */166	static stepIndex(step, traversal) {167		for (let i = 0; i < traversal.getSteps().size(); i++) {168			const s = traversal.getSteps().getValue(i);169			if (s === step) {170				return i;171			}172		}173		return -1;174	}175	static getStepsOfClass(stepClass, traversal) {176		const steps = new List();177		for (let i = 0; i < traversal.getSteps().size(); i++) {178			const step = traversal.getSteps().getValue(i);179			if (step.constructor.name === stepClass) {180				steps.add(step);181			}182		}183		return steps;184	}185	static getStepsOfAssignableClass(stepClass, traversal) {186		const steps = new List();187		for (let i = 0; i < traversal.getSteps().size(); i++) {188			const step = traversal.getSteps().getValue(i)189			if ((stepClass.TYPE && stepClass.TYPE === step.type) || step instanceof stepClass)190				steps.add(step);191		}192		return steps;193	}194	// public static <S> Optional<S> getLastStepOfAssignableClass(final Class<S> stepClass, final Traversal.Admin<?, ?> traversal) {195	//  final List<S> steps = TraversalHelper.getStepsOfAssignableClass(stepClass, traversal);196	//  return steps.size() == 0 ? Optional.empty() : Optional.of(steps.get(steps.size() - 1));197	// }198	 static getFirstStepOfAssignableClass(stepClass, traversal) {199		 for (let i = 0; i < traversal.getSteps().size(); i++) {200			 const step = traversal.getSteps().get(i);201	    if (stepClass === step || (stepClass.TYPE === 'Barrier' && step.barrierType))202	      return Optional.of(step);203	  }204	  return Optional.empty();205	 }206	static getStepsOfAssignableClassRecursively(scope, stepClass, traversal) {207		if (arguments.length === 2) {208			return TraversalHelper.getStepsOfAssignableClassRecursively(null, arguments[0], arguments[1]);209		}210		const list = new List();211		for (let i = 0; i < traversal.getSteps().size(); i++) {212			const step = traversal.getSteps().getValue(i);213			if (stepClass === step || (stepClass.TYPE && step.capableType === stepClass.TYPE))214				list.add(step);215			if (step.propType === TraversalParent.TYPE) {216				if (null === scope || Scope.local === scope) {217					for (let j = 0; j < step.getLocalChildren().size(); j++) {218						const localChild = step.getLocalChildren().getValue(j)219						list.addAll(TraversalHelper.getStepsOfAssignableClassRecursively(stepClass, localChild));220					}221				}222				if (null === scope || Scope.global === scope) {223					for (let j = 0; j < step.getGlobalChildren().size(); j++) {224						const globalChild = step.getGlobalChildren().getValue(j);225						list.addAll(TraversalHelper.getStepsOfAssignableClassRecursively(stepClass, globalChild));226					}227				}228			}229		}230		return list;231	}232	// public static boolean isGlobalChild(Traversal.Admin<?, ?> traversal) {233	//  while (!(traversal.getParent() instanceof EmptyStep)) {234	//    if (traversal.getParent().getLocalChildren().contains(traversal))235	//      return false;236	//    traversal = traversal.getParent().asStep().getTraversal();237	//  }238	//  return true;239	// }240	/**241	 * Determine if the traversal has a step of an assignable class.242	 *243	 * @param superClass the step super class to look for244	 * @param traversal  the traversal to perform the action on245	 * @return {@code true} if the class is found and {@code false} otherwise246	 */247	static hasStepOfAssignableClass(superClass, traversal) {248		for (let i = 0; i < traversal.getSteps().size(); i++) {249			const step = traversal.getSteps().getValue(i);250			if (superClass === step || step instanceof superClass) {251				return true;252			}253		}254		return false;255	}256	/**257	 * Determine if the traversal has any of the supplied steps of an assignable class in the current {@link Traversal}258	 * and its {@link Scope} child traversals.259	 *260	 * @param scope       whether to check global or local children (null for both).261	 * @param stepClasses the step classes to look for262	 * @param traversal   the traversal in which to look for the given step classes263	 * @return <code>true</code> if any step in the given traversal (and its child traversals) is an instance of a class264	 * provided in <code>stepClasses</code>, otherwise <code>false</code>.265	 */266	static hasStepOfAssignableClassRecursively(scope, stepClasses, traversal) {267		if (arguments.length === 2) {268			return this.hasStepOfAssignableClassRecursively(null, arguments[0], arguments[1]);269		}270		for (let i = 0; i < traversal.getSteps().size(); i++) {271			const step = traversal.getSteps().get(i);272			if (stepClasses instanceof List) {273				if (IteratorUtils.anyMatch(274						stepClasses.iterator(), (stepClass) => step instanceof stepClass || step.lambdaHolderType)) {275					return true;276				}277			} else {278				if (stepClasses === step || step instanceof stepClasses) {279					return true;280				}281			}282			if (step.propType === TraversalParent.TYPE) {283				if (!scope || Scope.local === scope) {284					for (let i = 0; i < step.getLocalChildren().size(); i++) {285						const localChild = step.getLocalChildren().getValue(i);286						if (this.hasStepOfAssignableClassRecursively(stepClasses, localChild)) return true;287					}288				}289				if (!scope || Scope.global === scope) {290					for (let i = 0; i < step.getGlobalChildren().size(); i++) {291						const globalChild = step.getGlobalChildren().getValue(i)292						if (this.hasStepOfAssignableClassRecursively(stepClasses, globalChild)) return true;293					}294				}295			}296		}297		return false;298	}299	/**300	 * Determine if any step in {@link Traversal} or its children match the step given the provided {@link Predicate}.301	 *302	 * @param predicate the match function303	 * @param traversal th traversal to perform the action on304	 * @return {@code true} if there is a match and {@code false} otherwise305	 */306	static anyStepRecursively(predicate, traversal) {307		if (traversal.asAdmin) {308			for (let i = 0; i < traversal.getSteps().size(); i++) {309				const step = traversal.getSteps().get(i);310				if (predicate(step)) {311					return true;312				}313				if (step.type === TraversalParent.TYPE) {314					return TraversalHelper.anyStepRecursivelyApply(predicate, step);315				}316			}317		} else {318			return TraversalHelper.anyStepRecursivelyApply(predicate, traversal);319		}320	}321	static anyStepRecursivelyApply(predicate, step) {322		for (let j = 0; j < step.getLocalChildren().size(); j++) {323			if (TraversalHelper.anyStepRecursively(predicate, step.getLocalChildren().get(j))) return true;324		}325		for (let j = 0; j < step.getGlobalChildren().size(); j++) {326			if (TraversalHelper.anyStepRecursively(predicate, step.getGlobalChildren().get(j))) return true;327		}328		return false;329	}330	/**331	 * Apply the provider {@link Consumer} function to the provided {@link Traversal} and all of its children.332	 *333	 * @param consumer  the function to apply to the each traversal in the tree334	 * @param traversal the root traversal to start application335	 */336	static applyTraversalRecursively(consumer, traversal) {337		consumer(traversal);338		for (let i = 0; i < traversal.getSteps().size(); i++) {339			const step = traversal.getSteps().get(i);340			if (step.propType === TraversalParent.TYPE) {341				for (let j = 0; j < step.getLocalChildren().size(); j++) {342					TraversalHelper.applyTraversalRecursively(consumer, step.getLocalChildren().get(j));343				}344				for (let j = 0; j < step.getGlobalChildren().size(); j++) {345					TraversalHelper.applyTraversalRecursively(consumer, step.getGlobalChildren().get(j));346				}347			}348		}349	}350	static addToCollection(collection, s, bulk) {351		for (let i = 0; i < bulk; i++) {352			collection.add(s);353		}354	}355	// /**356	// * @deprecated As of release 3.2.3, not replaced - only used by {@link org.apache.tinkerpop.gremlin.process.traversal.step.map.GroupStepV3d0}.357	// */358	// @Deprecated359	// public static <S> void addToCollectionUnrollIterator(final Collection<S> collection, final S s, final long bulk) {360	//  if (s instanceof Iterator) {361	//    ((Iterator<S>) s).forEachRemaining(r -> addToCollection(collection, r, bulk));362	//  } else if (s instanceof Iterable) {363	//    ((Iterable<S>) s).forEach(r -> addToCollection(collection, r, bulk));364	//  } else {365	//    addToCollection(collection, s, bulk);366	//  }367	// }368	//369	// /**370	// * Returns the name of <i>step</i> truncated to <i>maxLength</i>. An ellipses is appended when the name exceeds371	// * <i>maxLength</i>.372	// *373	// * @param step374	// * @param maxLength Includes the 3 "..." characters that will be appended when the length of the name exceeds375	// *                  maxLength.376	// * @return short step name.377	// */378	// public static String getShortName(final Step step, final int maxLength) {379	//  final String name = step.toString();380	//  if (name.length() > maxLength)381	//    return name.substring(0, maxLength - 3) + "...";382	//  return name;383	// }384	static reIdSteps(stepPosition, traversal) {385		stepPosition.x = 0;386		stepPosition.y = -1;387		stepPosition.z = -1;388		stepPosition.parentId = null;389		let current = traversal;390		while (!(current instanceof EmptyTraversal)) {391			stepPosition.y++;392			const parent = current.getParent();393			if (!stepPosition.parentId && !(parent instanceof EmptyStep)) {394				stepPosition.parentId = parent.asStep().getId();395			}396			if (stepPosition.z === -1) {397				const globalChildrenSize = parent.getGlobalChildren().size();398				for (let i = 0; i < globalChildrenSize; i++) {399					if (parent.getGlobalChildren().getValue(i) === current) {400						stepPosition.z = i;401					}402				}403				for (let i = 0; i < parent.getLocalChildren().size(); i++) {404					if (parent.getLocalChildren().getValue(i) === current) {405						stepPosition.z = i + globalChildrenSize;406					}407				}408			}409			current = parent.asStep().getTraversal();410		}411		if (stepPosition.z === -1) stepPosition.z = 0;412		if (!stepPosition.parentId) stepPosition.parentId = '';413		for (let i = 0; i < traversal.getSteps().size(); i++) {414			const step = traversal.getSteps().getValue(i);415			step.setId(stepPosition.nextXId());416		}417	}418	static getRootTraversal(traversal) {419		while (traversal.getParent().constructor.name !== 'EmptyStep') {420			traversal = traversal.getParent().asStep().getTraversal();421		}422		return traversal;423	}424	static getLabels() {425		if (arguments.length === 1) {426			const traversal = arguments[0];427			return TraversalHelper.getLabels(new List(), traversal);428		}429		const labels = arguments[0];430		const traversal = arguments[1];431		for (let i = 0; i < traversal.getSteps().size(); i++) {432			const step = traversal.getSteps().getValue(i);433			labels.addAll(step.getLabels());434			if (step.propType === TraversalParent.TYPE) {435				for (let j = 0; j < step.getLocalChildren().size(); j++) {436					const local = step.getLocalChildren().getValue(j);437					TraversalHelper.getLabels(labels, local);438				}439				for (let j = 0; j < step.getGlobalChildren().size(); j++) {440					const global = step.getGlobalChildren().getValue(j);441					TraversalHelper.getLabels(labels, global);442				}443			}444		}445		return labels;446	}447	static getVariableLocations() {448		if (arguments.length === 1) {449			const traversal = arguments[0];450			return TraversalHelper.getVariableLocations(new List(), traversal);451		}452		const variables = arguments[0];453		const traversal = arguments[1];454		if (variables.size() === 2) return variables;    // has both START and END so no need to compute further455		const startStep = traversal.getStartStep();456		if (StartStep.isVariableStartStep(startStep))457			variables.add(Scoping.Variable.START);458		else if (startStep instanceof WherePredicateStep) {459			if (startStep.getStartKey().isPresent())460				variables.add(Scoping.Variable.START);461		} else if (startStep instanceof WhereTraversalStep.WhereStartStep) {462			if (!startStep.getScopeKeys().isEmpty())463				variables.add(Scoping.Variable.START);464		} else if (startStep instanceof MatchStep.MatchStartStep) {465			if (startStep.getSelectKey().isPresent())466				variables.add(Scoping.Variable.START);467		} else if (startStep instanceof MatchStep) {468			for (let i = 0; i < startStep.getGlobalChildren().size(); i++) {469				const global = startStep.getGlobalChildren().getValue(i);470				TraversalHelper.getVariableLocations(variables, global);471			}472		} else if (startStep instanceof ConnectiveStep || startStep instanceof NotStep || startStep instanceof WhereTraversalStep) {473			for (let i = 0; i < startStep.getLocalChildren().size(); i++) {474				const local = startStep.getLocalChildren().getValue(i);475				TraversalHelper.getVariableLocations(variables, local);476			}477		}478		///479		const endStep = traversal.getEndStep();480		if (endStep instanceof WherePredicateStep) {481			if (endStep.getStartKey().isPresent())482				variables.add(Scoping.Variable.END);483		} else if (endStep instanceof WhereTraversalStep.WhereEndStep) {484			if (!endStep.getScopeKeys().isEmpty())485				variables.add(Scoping.Variable.END);486		} else if (endStep instanceof MatchStep.MatchEndStep) {487			if (endStep.getMatchKey().isPresent())488				variables.add(Scoping.Variable.END);489		} else if (!endStep.getLabels().isEmpty())490			variables.add(Scoping.Variable.END);491		///492		return variables;493	}494	static onGraphComputer(traversal) {495		//while (!(traversal.getParent() instanceof EmptyStep)) {496		//  if (traversal.getParent() instanceof TraversalVertexProgramStep)497		//    return true;498		//  traversal = traversal.getParent().asStep().getTraversal();499		//}500		return false;501	}502	//503	// public static void removeAllSteps(final Traversal.Admin<?, ?> traversal) {504	//  final int size = traversal.getSteps().size();505	//  for (int i = 0; i < size; i++) {506	//    traversal.removeStep(0);507	//  }508	// }509	//510	static copyLabels(fromStep, toStep, moveLabels) {511		if (!fromStep.getLabels().isEmpty()) {512			const labels = fromStep.getLabels();513			for (let i = 0; i < labels.size(); i++) {514				const label = labels.getValue(i);515				toStep.addLabel(label);516				if (moveLabels) {517					fromStep.removeLabel(label);518				}519			}520		}521	}522	static hasAllStepsOfClass(traversal, ...classesToCheck) {523		classesToCheck = ArrayUtils.checkArray(classesToCheck);524		for (let i = 0; i < traversal.getSteps().size(); i++) {525			const step = traversal.getSteps().getValue(i);526			let foundInstance = false;527			for (let j = 0; j < classesToCheck.length; j++) {528				const classToCheck = classesToCheck[j];529				if (classToCheck.TYPE === step.type) {530					foundInstance = true;531					break;532				}533			}534			if (!foundInstance)535				return false;536		}537		return true;538	}539	static hasStepOfClass(traversal, ...classesToCheck) {540		if (traversal.asAdmin) {541			classesToCheck = ArrayUtils.checkArray(classesToCheck);542			for (let i = 0; i < traversal.getSteps().size(); i++) {543				const step = traversal.getSteps().getValue(i);544				for (let j = 0; j < classesToCheck.length; j++) {545					const classToCheck = classesToCheck[j];546					if (classToCheck.TYPE === step.type)547						return true;548				}549			}550		} else {551			const stepClass = arguments[0];552			traversal = arguments[1];553			for (let i = 0; i < traversal.getSteps().size(); i++) {554				const step = traversal.getSteps().getValue(i);555				if (step === stepClass) {556					return true;557				}558			}559		}560		return false;561	}562	static applySingleLevelStrategies(parentTraversal, childTraversal, stopAfterStrategy) {563		childTraversal.setStrategies(parentTraversal.getStrategies());564		childTraversal.setSideEffects(parentTraversal.getSideEffects());565		childTraversal.setGraph(parentTraversal.getGraph());566		for (let i = 0; i < parentTraversal.getStrategies().traversalStrategies.size(); i++) {567			const strategy = parentTraversal.getStrategies().traversalStrategies.get(i);568			strategy.apply(childTraversal);...

Full Screen

Full Screen

Page.js

Source:Page.js Github

copy

Full Screen

...28    return result;29  },30  addSnapshot : function() {31    return this.addStep(function(key, callback) {32      var result = this.getSteps().add('snapshot', {}, key);33      result.activate(callback);34      return result;35    });36  },37  addEvent : function(e, frames) {38    return this.addStep(function(key, callback) {39      var result = this.getSteps().add('event', {40        event : e,41        frames : frames42      }, key);43      callback && callback();44      return result;45    });46  },47  addInput: function(e, frames) {48    return this.addStep(function(key, callback) {49      var result = this.getSteps().add('input', {50        event : e,51        frames : frames52      }, key);53      callback && callback();54      return result;55    });56  },57  addWatcher : function(options) {58    return this.addStep(function(key, callback) {59      var result = this.getSteps().add('watcher', options, key);60      if (!options) {61        result.activate(callback);62      }63      else {64        callback && callback();65      }66      return result;67    });68  },69  addCall : function() {70    return this.addStep(function(key, callback) {71      var result = this.getSteps().add('call', {}, key);72      callback && callback();73      return result;74    });75  },76  updateDelay : function(val) {77    this.options.delay = val;78  },79  addQuery : function() {80    return this.addStep(function(key, callback) {81      var result = this.getSteps().add('query', {}, key);82      callback && callback();83      return result;84    });85  },86  getSteps : function() {87    return this.getObject('steps')[0];88  },89  getItems : function() {90    return this.getSteps().tmp;91  },92  checkItem : function() {93    return false;94  },95  record : function(callback) {96    //this.goLast(callback);97  },98  test : function(callback, to, record) {99    var location = this.getParent('test').getLocation();100    var url = this.getURL();101    if (url && url !== location) {102      this.addError({type : 'page', message : 'bad path'});103      this.log('Bad path : "' + location + '"');104    }105    else {106      this.log('Test');107      this.testPage(callback, to, record);108    }109  },110  testPage: function(callback, to, record) {111    var current = this.getCurrent();112    var all = this.getSteps().tmp;113    this.getParent('test').goPage(this);114    this.select();115    if (to !== undefined) {116      if (to <= current) {117        this.testNextItem(all.slice(0, to + 1), 0, callback, record);118        this.setCurrent(to);119      }120      else {121        this.setCurrent(to);122        if (to < 0) {123          start = 0;124          end = 0;125        }126        else {127          var start = current + 1;128          var end = to + 1;129        }130        this.testNextItem(all.slice(start, end), 0, callback, record);131      }132    }133    else {134      this.setCurrent(all.length - 1);135      this.testNextItem(all, 0, callback);136    }137  },138  selectStep : function(step) {139    step.setReady(true);140  },141  resetSteps : function(mode) {142    mode = mode || this.mode.played;143    //this.setCurrent();144    this.getSteps().tmp.each(function(item) {145      if (mode & this.mode.ready) item.isReady(false);146      if (mode & this.mode.played) item.isPlayed(false);147    }.bind(this));148  },149  /**150   * function callback151   * bool reload reload page152   */153  go : function(callback, reload) {154    var location = this.getWindow().location;155    this.getParent('test').goPage(this);156    var current = location.pathname + location.search;157    var url = this.getURL();158    var diff = url && current !== url;159    if (!this.errors.length && (reload || diff)) {160      this.resetSteps(this.mode.all);161      this.setCurrent(-1);162      if (url) {163        location.href = url || location.href;164        this.getParent('main').pauseRecord();165        this.getParent('main').preparePage(function() {166          this.select(function() {167            callback && callback();168            this.getParent('main').resumeRecord();169          }.bind(this));170        }.bind(this));171        if (reload && !diff || !url) {172          this.getWindow().location.reload();173        }174      }175      else {176        this.select(callback);177      }178    }179    else {180      this.select(callback);181    }182  },183  goTest : function(callback) {184    this.go(function() {185      this.test(callback);186    }.bind(this), true);187  },188  goStep: function(step, callback) {189    var key = step.getKey();190    this.resetSteps(this.mode.ready);191    this.getParent('main').pauseRecord();192    var select = function() {193      step.isReady(true);194      callback && callback();195      this.getParent('main').resumeRecord();196    }.bind(this);197    this.isgo = true;198    var reload = !this.isActive() || key <= this.getCurrent();199    if (key !== this.getCurrent()) {200      this.go(function() {201        this.test(select, key);202      }.bind(this), reload);203    }204    else {205      select();206    }207  },208  getURL : function() {209    var parser = this.parseVariables(this.get('url'));210    if (parser.variables) {211      this.getNode('name').set('href', parser.content);212    }213    else if (!parser.content) {214      this.getNode('name').set('href', this.getWindow().location.href);215    }216    return parser.content;217  },218  goURL : function() {219    var location = this.getWindow().location;220    location.href = this.getURL();221  },222  updateName: function() {223    var result = this.options.url;224    this.getNode('name').set({225      html : result ? result : '[any]',226      href : result ? result : '#'227    });228  },229  setFile : function(val, update) {230    this.options.url = val;231    if (update === undefined || update) {232      this.updateName();233    }234  },235  select : function(callback, reset) {236    this.getParent('test').updateFrameSize();237    if (reset) {238      this.setCurrent(-1);239      this.go(function() {240        this.toggleActivation(true);241        this.test(callback, -1);242      }.bind(this), true);243    }244    else {245      callback && callback();246      this.toggleActivation(true);247    }248  },249  unselect : function() {250    this.setCurrent(-1);251    this.toggleActivation(false);252    this.resetSteps(this.mode.all);253  },254  testItems : function(items, key, callback, record) {255    key = key || 0;256    var item = items[key];257    item.hasError(false);258    item.isReady(false);259    item.test(function() {260      item.isPlayed(true);261      this.testNextItem(items, key + 1, callback, record);262    }.bind(this));263  },264  testLast : function(items, key, callback, record) {265    var item = items[key];266    var all = this.getSteps().tmp;267    var test = this.getParent('test');268    var lastPage = test.getObject('page').getLast();269    if (!this.isgo && !record && item == all.getLast() && this != lastPage) {270      if (item.getAlias() === 'event') {271        this.getParent('main').preparePage(callback);272        this.testItem(items, key);273      }274      else {275        this.testItem(items, key, function() {276          test.getObject('page')[this.getKey() + 1].go(callback, true);277        }.bind(this));278      }279    }280    else {281      this.isgo = false;282      this.testItem(items, key, callback);283    }284  },285  toJSON : function() {286    var result = {287      '@url' : this.get('url'),288      steps : this.getSteps().tmp289    };290    return result;291  },292  asToken : function() {293    return 'page(' + this.getKey() + ') : ' + this.options.url;294  }...

Full Screen

Full Screen

App.js

Source:App.js Github

copy

Full Screen

...20        ...this.props.form.getFieldsValue(),21      },22    });23    const currentStep = this.getCurrentStep();24    if (currentStep < this.getSteps().length - 1) {25      this.pushUrl(this.getSteps()[currentStep + 1].path);26    } else {27      Modal.success({28        title: "提交成功",29      });30    }31  };32  handleBack = () => {33    console.log("form values: ", this.props.form.getFieldsValue());34    this.setState({35      allValues: {36        ...this.state.allValues,37        ...this.props.form.getFieldsValue(),38      },39    });40    const currentStep = this.getCurrentStep();41    if (currentStep > 0) {42      this.pushUrl(this.getSteps()[currentStep - 1].path);43    }44  };45  getCurrentStep() {46    const currentPath = document.location.hash.replace(/^#/, "");47    return _.findIndex(this.getSteps(), { path: currentPath });48  }49  getSteps() {50    return [51      { title: "验证邮件", path: "/wizard/step/1", component: Step1 },52      { title: "账号信息", path: "/wizard/step/2", component: Step2 },53      { title: "完成", path: "/wizard/step/3", component: Step3 },54    ];55  }56  renderComponent = () => {57    const StepComponent = this.getSteps()[this.getCurrentStep()].component;58    return (59      <StepComponent form={this.props.form} allValues={this.state.allValues} />60    );61  };62  render() {63    if (!/^#\/wizard\/step/.test(document.location.hash)) {64      return (65        <Button type="primary" onClick={() => this.pushUrl("/wizard/step/1")}>66          创建账号67        </Button>68      );69    }70    return (71      <Router>72        <Form>73          <div style={{ width: "600px" }}>74            <h1>创建账号</h1>75            <Steps current={this.getCurrentStep()}>76              {this.getSteps().map(step => <Steps.Step title={step.title} />)}77            </Steps>78            <div className="step-container" style={{ margin: "40px 0" }}>79              <Route80                path="/wizard/step/:stepId"81                render={this.renderComponent}82              />83            </div>84            <div>85              <Button86                disabled={this.getCurrentStep() === 0}87                onClick={this.handleBack}88                style={{ marginRight: "20px" }}89              >90                上一步91              </Button>92              <Button onClick={this.handleNext} type="primary">93                {this.getCurrentStep() === this.getSteps().length - 194                  ? "完成"95                  : "下一步"}96              </Button>97            </div>98          </div>99        </Form>100      </Router>101    );102  }103}...

Full Screen

Full Screen

prerequisites.spec.js

Source:prerequisites.spec.js Github

copy

Full Screen

1const utils = require('./utils');2const plugin = require('..');3describe('Execution prerequisites', () => {4  it('should return no pipeline when asking for unwanted when', () => {5    const steps = utils.getSteps(`6  post:7    - when: failure8      steps: |9        - label: step110          command: step1.sh11  `);12    const pipeline = plugin.pipeline('success', steps);13    expect(pipeline).toEqual(undefined);14  });15  it('should fail when declaring an unknown when', () => {16    const steps = utils.getSteps(`17  post:18    - when: wtf19      steps: |20        - label: step121          command: step1.sh22  `);23    expect(() => {24      plugin.pipeline('success', steps);25    }).toThrow(/"when: wtf" is not recognized./);26  });27  it('should fail when getting an unknown when', () => {28    const steps = utils.getSteps(`29  post:30    - when: success31      steps: |32        - label: step133          command: step1.sh34  `);35    expect(() => {36      plugin.pipeline('wtf', steps);37    }).toThrow(/"when: wtf" is not recognized./);38  });39  it('should fail with missing when', () => {40    const steps = utils.getSteps(`41  post:42    - steps: |43        - label: step144          command: step1.sh45  `);46    expect(() => {47      plugin.pipeline('success', steps);48    }).toThrow(/"post" object must include/);49  });50  it('should fail with missing steps', () => {51    const steps = utils.getSteps(`52  post:53    - when: success54  `);55    expect(() => {56      plugin.pipeline('success', steps);57    }).toThrow(/"post" object must include/);58  });59  it('should fail with missing config', () => {60    const steps = utils.getSteps(``);61    expect(() => {62      plugin.pipeline('success', steps);63    }).toThrow(/Missing plugin config/);64  });65  it('should fail with wait on failure', () => {66    const steps = utils.getSteps(`67  post:68  - when: failure69    steps: |70      - label: step171        command: step1.sh72        wait: ~73`);74    expect(() => {75      plugin.pipeline('failure', steps);76    }).toThrow(/Unsupported post layout/);77  });78  it('should fail with paralallel jobs', () => {79    const steps = utils.getSteps(`80  post:81  - when: failure82    steps: |83      - label: step184        command: step1.sh85        parallelism: 286`);87    expect(() => {88      plugin.pipeline('failure', steps);89    }).toThrow(/Unsupported post layout/);90  });91  it('should fail with implicit paralallel jobs', () => {92    const steps = utils.getSteps(`93  post:94  - when: failure95    steps: |96      - label: step197        command: step1.sh98        parallelism: 299`);100    expect(() => {101      plugin.pipeline('failure', steps);102    }).toThrow(/Unsupported post layout/);103  });104  it('should fail with explicit paralallel jobs', () => {105    const steps = utils.getSteps(`106  post:107  - when: failure108    steps: |109      - label: step1110        command: step1.sh111      - label: step1112        command: step1.sh113      - wait114      - label: step1115        command: step1.sh116`);117    expect(() => {118      plugin.pipeline('failure', steps);119    }).toThrow(/Unsupported post layout/);...

Full Screen

Full Screen

dataservice.js

Source:dataservice.js Github

copy

Full Screen

...20            getPremiumCalculator: getPremiumCalculator,21            addClient: addClient22        };23        return service;24        function getSteps() {25            if (!steps.length) {26                steps = $window.steps;27            }28            return steps;29        }30        function getFirstStep() {31            return getSteps()[0];32        }33        function getStep(state) {34            var step = _.find(getSteps(), {'state': state});35            return step;36        }37        function activateStep(step) {38            step.isActive = true;39        }40        function deactivateStep(step) {41            step.isActive = false;42        }43        function getNextStep(state) {44            var step = getStep(state);45            var idx = getStepIndex(step);46            var nextStep = getSteps()[idx + 1];47            return nextStep;48        }49        function getPrevStep(state) {50            var step = getStep(state);51            var idx = getStepIndex(step);52            var prevStep = getSteps()[idx - 1];53            return prevStep;54        }55        function redirectUnlessActive(step) {56            if(!step.isActive) {57                var lastStep = getActiveStep();58                if(lastStep) {59                    $state.go(lastStep.state);60                } else {61                    $state.go('/');62                }63            }64        }65        function getStepIndex(step) {66            return _.indexOf(getSteps(), step);67        }68        function getActiveStep() {69            return _.findLast(steps, 'isActive', true);70        }71        function getPremiumCalculator() {72            return premiumCalculator;73        }74        function addClient() {75        }76    }...

Full Screen

Full Screen

StepsService.js

Source:StepsService.js Github

copy

Full Screen

...18        this.getSteps = function(){19            return $stateParams.deploySteps;20        };21        this.getCurrentStep = function getCurrentStep(){22            return _.find(me.getSteps(), me.isCurrentStep );23        };24        this.getRelativeStep = function( relation ){25            // very inefficient, but in real world no effect26            var currentStepIndex = _.indexOf(me.getSteps(),me.getCurrentStep());27            var goToIndex = currentStepIndex + relation;28            return me.getSteps()[goToIndex];29        };30        this.nextStep = function(){31            me.goToStep(me.getRelativeStep(1));32        };33        this.previousStep = function(){34            me.goToStep(me.getRelativeStep(-1));35        };36        this.hasNextStep = function hasNextStep(){37            return !me.isCurrentStep(_.last(me.getSteps()));38        };39        this.hasPreviousStep = function hasPreviousStep(){40            return !me.isCurrentStep(_.first(me.getSteps()));41        };...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var Cucumber = require('cucumber');2var fs = require('fs');3var gherkin = fs.readFileSync('test.feature', 'utf8');4var parser = new Cucumber.Parser();5var features = parser.parse(gherkin);6var feature = features[0];7var scenario = feature.getScenarios()[0];8var steps = scenario.getSteps();9steps.forEach(function(step) {10  console.log(step.getKeyword() + step.getName());11});12var Cucumber = require('../../cucumber');13    at Object.<anonymous> (C:\Users\test14    at Module._compile (module.js:556:32)15    at Object.Module._extensions..js (module.js:565:10)16    at Module.load (module.js:473:32)17    at tryModuleLoad (module.js:432:12)18    at Function.Module._load (module.js:424:3)19    at Module.require (module.js:483:17)20    at require (internal/module.js:20:19)21    at Object.<anonymous> (C:\Users\test22    at Module._compile (module.js:556:32)

Full Screen

Using AI Code Generation

copy

Full Screen

1var gherkin = require('cucumber-gherkin');2var fs = require('fs');3var file = fs.readFileSync('test.feature', 'utf8');4var options = {5};6var result = gherkin.fromSources([file], options);7var steps = result[0].feature.children[0].steps;8var step = steps[0];9console.log(step.keyword);10console.log(step.text);11Your name to display (optional):

Full Screen

Using AI Code Generation

copy

Full Screen

1var cucumber = require('cucumber');2var fs = require('fs');3var featureFile = fs.readFileSync('test.feature', 'utf8');4var feature = cucumber.parse(featureFile);5var steps = feature.getSteps();6console.log(steps);7[ { getKeyword: [Function],8    getUri: [Function] },9  { getKeyword: [Function],10    getUri: [Function] },11  { getKeyword: [Function],12    getUri: [Function] } ]13var cucumber = require('cucumber');14var gherkin = require('gherkin');

Full Screen

Using AI Code Generation

copy

Full Screen

1var gherkin = require('gherkin');2var fs = require('fs');3var gherkinFile = fs.readFileSync('test.feature', 'utf-8');4var parser = new gherkin.Parser();5var feature = parser.parse(gherkinFile);6var keyword = "Given";7var steps = feature.getSteps(keyword);8console.log(steps);9var keyword = "When";10var steps = feature.getSteps(keyword);11console.log(steps);12var keyword = "Then";13var steps = feature.getSteps(keyword);14console.log(steps);

Full Screen

Using AI Code Generation

copy

Full Screen

1var getSteps = require("cucumber-gherkin").getSteps;2var steps = getSteps();3console.log(steps);4var getSteps = require("cucumber-gherkin").getSteps;5var steps = getSteps();6console.log(steps);7var getSteps = require("cucumber-gherkin").getSteps;8var steps = getSteps();9console.log(steps);10var getSteps = require("cucumber-gherkin").getSteps;11var steps = getSteps();12console.log(steps);13var getSteps = require("cucumber-gherkin").getSteps;14var steps = getSteps();15console.log(steps);16var getSteps = require("cucumber-gherkin").getSteps;17var steps = getSteps();18console.log(steps);19var getSteps = require("cucumber-gherkin").getSteps;20var steps = getSteps();21console.log(steps);22var getSteps = require("cucumber-gherkin").getSteps;23var steps = getSteps();24console.log(steps);25var getSteps = require("cucumber-gherkin").getSteps;26var steps = getSteps();27console.log(steps);28var getSteps = require("cucumber-gherkin").getSteps;29var steps = getSteps();30console.log(steps);31var getSteps = require("cucumber-gherkin").getSteps;32var steps = getSteps();33console.log(steps);34var getSteps = require("cucumber-gherkin").getSteps;35var steps = getSteps();36console.log(steps);37var getSteps = require("cucumber-gherkin").getSteps;38var steps = getSteps();39console.log(steps);40var getSteps = require("cucumber-gherkin").getSteps;41var steps = getSteps();42console.log(steps);

Full Screen

Using AI Code Generation

copy

Full Screen

1var gherkin = require('gherkin');2var parser = new gherkin.Parser();3    Then my belly should growl";4var feature = parser.parse(featureSource);5var steps = feature.getSteps();6for(var i=0;i<steps.length;i++){7    console.log(steps[i].getName());8}

Full Screen

Using AI Code Generation

copy

Full Screen

1var gherkin = require('cucumber-gherkin');2var fs = require('fs');3var path = require('path');4var Cucumber = require('cucumber');5var gherkin = require('cucumber-gherkin');6var fs = require('fs');7var path = require('path');8var Cucumber = require('cucumber');9var gherkin = require('cucumber-gherkin');10var fs = require('fs');11var path = require('path');12var Cucumber = require('cucumber');13var gherkin = require('cucumber-gherkin');14var fs = require('fs');15var path = require('path');16var Cucumber = require('cucumber');17var gherkin = require('cucumber-gherkin');18var fs = require('fs');19var path = require('path');20var Cucumber = require('cucumber');21var gherkin = require('cucumber-gherkin');22var fs = require('fs');23var path = require('path');24var Cucumber = require('cucumber');25var gherkin = require('cucumber-gherkin');26var fs = require('fs');27var path = require('path');

Full Screen

Cucumber Tutorial:

LambdaTest offers a detailed Cucumber testing tutorial, explaining its features, importance, best practices, and more to help you get started with running your automation testing scripts.

Cucumber Tutorial Chapters:

Here are the detailed Cucumber testing chapters to help you get started:

  • Importance of Cucumber - Learn why Cucumber is important in Selenium automation testing during the development phase to identify bugs and errors.
  • Setting Up Cucumber in Eclipse and IntelliJ - Learn how to set up Cucumber in Eclipse and IntelliJ.
  • Running First Cucumber.js Test Script - After successfully setting up your Cucumber in Eclipse or IntelliJ, this chapter will help you get started with Selenium Cucumber testing in no time.
  • Annotations in Cucumber - To handle multiple feature files and the multiple scenarios in each file, you need to use functionality to execute these scenarios. This chapter will help you learn about a handful of Cucumber annotations ranging from tags, Cucumber hooks, and more to ease the maintenance of the framework.
  • Automation Testing With Cucumber And Nightwatch JS - Learn how to build a robust BDD framework setup for performing Selenium automation testing by integrating Cucumber into the Nightwatch.js framework.
  • Automation Testing With Selenium, Cucumber & TestNG - Learn how to perform Selenium automation testing by integrating Cucumber with the TestNG framework.
  • Integrate Cucumber With Jenkins - By using Cucumber with Jenkins integration, you can schedule test case executions remotely and take advantage of the benefits of Jenkins. Learn how to integrate Cucumber with Jenkins with this detailed chapter.
  • Cucumber Best Practices For Selenium Automation - Take a deep dive into the advanced use cases, such as creating a feature file, separating feature files, and more for Cucumber testing.

Run Cucumber-gherkin automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful