How to use pickleTags method in Cucumber-gherkin

Best JavaScript code snippet using cucumber-gherkin

gherkin.js

Source:gherkin.js Github

copy

Full Screen

...6071    scenario.steps.forEach(function (step) {6072      steps.push(pickleStep(step));6073    });6074    var pickle = {6075      tags: pickleTags(tags),6076      name: scenario.name,6077      language: language,6078      locations: [pickleLocation(scenario.location)],6079      steps: steps6080    };6081    pickles.push(pickle);6082  }6083  function compileScenarioOutline(featureTags, backgroundSteps, scenarioOutline, language, pickles) {6084    scenarioOutline.examples.filter(function(e) { return e.tableHeader != undefined; }).forEach(function (examples) {6085      var variableCells = examples.tableHeader.cells;6086      examples.tableBody.forEach(function (values) {6087        var valueCells = values.cells;6088        var steps = scenarioOutline.steps.length == 0 ? [] : [].concat(backgroundSteps);6089        var tags = [].concat(featureTags).concat(scenarioOutline.tags).concat(examples.tags);6090        scenarioOutline.steps.forEach(function (scenarioOutlineStep) {6091          var stepText = interpolate(scenarioOutlineStep.text, variableCells, valueCells);6092          var args = createPickleArguments(scenarioOutlineStep.argument, variableCells, valueCells);6093          var pickleStep = {6094            text: stepText,6095            arguments: args,6096            locations: [6097              pickleLocation(values.location),6098              pickleStepLocation(scenarioOutlineStep)6099            ]6100          };6101          steps.push(pickleStep);6102        });6103        var pickle = {6104          name: interpolate(scenarioOutline.name, variableCells, valueCells),6105          language: language,6106          steps: steps,6107          tags: pickleTags(tags),6108          locations: [6109            pickleLocation(values.location),6110            pickleLocation(scenarioOutline.location)6111          ]6112        };6113        pickles.push(pickle);6114      });6115    });6116  }6117  function createPickleArguments(argument, variableCells, valueCells) {6118    var result = [];6119    if (!argument) return result;6120    if (argument.type === 'DataTable') {6121      var table = {6122        rows: argument.rows.map(function (row) {6123          return {6124            cells: row.cells.map(function (cell) {6125              return {6126                location: pickleLocation(cell.location),6127                value: interpolate(cell.value, variableCells, valueCells)6128              };6129            })6130          };6131        })6132      };6133      result.push(table);6134    } else if (argument.type === 'DocString') {6135      var docString = {6136        location: pickleLocation(argument.location),6137        content: interpolate(argument.content, variableCells, valueCells),6138      };6139      if(argument.contentType) {6140        docString.contentType = interpolate(argument.contentType, variableCells, valueCells);6141      }6142      result.push(docString);6143    } else {6144      throw Error('Internal error');6145    }6146    return result;6147  }6148  function interpolate(name, variableCells, valueCells) {6149    variableCells.forEach(function (variableCell, n) {6150      var valueCell = valueCells[n];6151      var search = new RegExp('<' + variableCell.value + '>', 'g');6152      // JS Specific - dollar sign needs to be escaped with another dollar sign6153      // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_string_as_a_parameter6154      var replacement = valueCell.value.replace(new RegExp('\\$', 'g'), '$$$$')6155      name = name.replace(search, replacement);6156    });6157    return name;6158  }6159  function pickleSteps(scenarioDefinition) {6160    return scenarioDefinition.steps.map(function (step) {6161      return pickleStep(step);6162    });6163  }6164  function pickleStep(step) {6165    return {6166      text: step.text,6167      arguments: createPickleArguments(step.argument, [], []),6168      locations: [pickleStepLocation(step)]6169    }6170  }6171  function pickleStepLocation(step) {6172    return {6173      line: step.location.line,6174      column: step.location.column + (step.keyword ? countSymbols(step.keyword) : 0)6175    };6176  }6177  function pickleLocation(location) {6178    return {6179      line: location.line,6180      column: location.column6181    }6182  }6183  function pickleTags(tags) {6184    return tags.map(function (tag) {6185      return pickleTag(tag);6186    });6187  }6188  function pickleTag(tag) {6189    return {6190      name: tag.name,6191      location: pickleLocation(tag.location)6192    };6193  }6194}6195module.exports = Compiler;6196},{"../count_symbols":4}],12:[function(require,module,exports){6197function Token(line, location) {...

Full Screen

Full Screen

cucumber-reportportal-formatter.spec.js

Source:cucumber-reportportal-formatter.spec.js Github

copy

Full Screen

1/* These tests need to be rewritten to reflect the refactoring of the agent. Plans for version 5.0.1. */2const { createRPFormatterClass } = require('../modules');3const {4  ContextMock,5  DocumentsStorageMock,6  RPClientMock,7  getDefaultConfig,8  mockedDate,9} = require('./mocks');10const itemFinders = require('../modules/itemFinders');11const utils = require('../modules/utils');12const { AFTER_HOOK_URI_TO_SKIP, STATUSES } = require('../modules/constants');13const featureMock = {14  description: 'feature description',15  keyword: 'ft',16  name: 'feature',17  tags: ['@feature:value'],18  children: [],19};20describe('Create ReportPortal formatter class', function() {21  let FormatterClass;22  let formatter;23  beforeEach(() => {24    const config = getDefaultConfig();25    FormatterClass = createRPFormatterClass(config);26    formatter = new FormatterClass({27      parsedArgvOptions: {},28      eventBroadcaster: {29        on: () => {},30      },31    });32    formatter.contextState = new ContextMock();33    formatter.documentsStorage = new DocumentsStorageMock();34    formatter.reportportal = new RPClientMock();35    formatter.attributesConf = [];36  });37  afterEach(() => {38    jest.clearAllMocks();39  });40  describe('onGherkinDocument', () => {41    const documentEvent = {42      uri: 'mockUri',43      document: 'any',44      pickle: null,45    };46    test('should call cacheDocument method from documents storage to cache the document', function() {47      const spyCacheDocument = jest.spyOn(formatter.documentsStorage, 'cacheDocument');48      formatter.onGherkinDocument(documentEvent);49      expect(spyCacheDocument).toHaveBeenCalledWith(documentEvent);50    });51    test('should call startLaunch method from RPClient if not launchId in the config', function() {52      const launchStartObj = {53        name: 'LauncherName',54        startTime: mockedDate,55        description: 'Launch description',56        attributes: [],57        rerun: undefined,58        rerunOf: undefined,59      };60      const spyStartLaunch = jest.spyOn(formatter.reportportal, 'startLaunch');61      formatter.onGherkinDocument(documentEvent);62      expect(spyStartLaunch).toHaveBeenCalledWith(launchStartObj);63      expect(formatter.contextState.context.launchId).toBe('tempLaunchId');64    });65    test('should not call startLaunch method from RPClient if launchId exists in the config', function() {66      formatter.contextState.context.launchId = 'tempLaunchId';67      const spyStartLaunch = jest.spyOn(formatter.reportportal, 'startLaunch');68      formatter.onGherkinDocument(documentEvent);69      expect(spyStartLaunch).toHaveBeenCalledTimes(0);70    });71  });72  describe('onPickleAccepted', () => {73    const uriMock = 'featureUri';74    const documentEvent = {75      uri: uriMock,76      document: 'any',77      pickle: null,78    };79    beforeAll(() => {80      jest.spyOn(itemFinders, 'findFeature').mockImplementation(() => featureMock);81      jest.spyOn(itemFinders, 'findBackground').mockReturnValue(null);82      jest.spyOn(utils, 'getUri').mockReturnValue(uriMock);83      jest.spyOn(utils, 'createAttribute').mockReturnValue([{ key: 'feature', value: 'value' }]);84    });85    beforeEach(() => {86      formatter.documentsStorage.pickleDocuments[uriMock] = {};87    });88    test('should call isAcceptedPickleCached method from documents storage with event', function() {89      const spyIsAcceptedPickleCached = jest.spyOn(90        formatter.documentsStorage,91        'isAcceptedPickleCached',92      );93      formatter.onPickleAccepted(documentEvent);94      expect(spyIsAcceptedPickleCached).toHaveBeenCalledWith(documentEvent);95    });96    test('should call cacheAcceptedPickle method from documents storage if pickle not cached', function() {97      const spyCacheAcceptedPickle = jest.spyOn(formatter.documentsStorage, 'cacheAcceptedPickle');98      formatter.onPickleAccepted(documentEvent);99      expect(spyCacheAcceptedPickle).toHaveBeenCalledWith(documentEvent);100    });101    test('should not call cacheAcceptedPickle method from documents storage if pickle cached', function() {102      jest.spyOn(formatter.documentsStorage, 'isAcceptedPickleCached').mockReturnValue(true);103      const spyCacheAcceptedPickle = jest.spyOn(formatter.documentsStorage, 'cacheAcceptedPickle');104      formatter.onPickleAccepted(documentEvent);105      expect(spyCacheAcceptedPickle).toHaveBeenCalledTimes(0);106    });107  });108  describe('onTestCasePrepared', () => {109    test('should set stepDefinitions and isBeforeHook for the context', function() {110      const event = {111        data: 'any',112      };113      formatter.onTestCasePrepared(event);114      expect(formatter.contextState.context.stepDefinitions).toEqual(event);115      expect(formatter.contextState.context.isBeforeHook).toBe(true);116    });117  });118  describe('onTestCaseStarted', () => {119    const uriMock = 'featureUri';120    const documentEvent = {121      uri: uriMock,122      document: 'any',123      name: 'lol',124      keyword: 'loc',125      description: 'description',126      sourceLocation: {127        uri: uriMock,128      },129    };130    const pickleTags = [131      {132        name: '@feature:value',133        location: {134          line: 1,135          column: 1,136        },137      },138    ];139    let spyFindScenario;140    let spyGetUri;141    let spyCreateAttributes;142    let spyCreateTagComparator;143    beforeAll(() => {144      spyFindScenario = jest145        .spyOn(itemFinders, 'findScenario')146        .mockImplementation(() => featureMock);147      spyGetUri = jest.spyOn(utils, 'getUri').mockReturnValue(uriMock);148      spyCreateAttributes = jest149        .spyOn(utils, 'createAttributes')150        .mockReturnValue([{ key: 'feature', value: 'value' }]);151      spyCreateTagComparator = jest152        .spyOn(utils, 'createTagComparator')153        .mockReturnValue(() => false);154    });155    beforeEach(() => {156      formatter.documentsStorage.pickleDocuments[uriMock] = {157        featureId: 'featureId',158        tags: pickleTags,159      };160      formatter.documentsStorage.gherkinDocuments[uriMock] = {161        feature: {162          tags: [],163        },164      };165    });166    test('should call findScenario with gherkinDocuments & sourceLocation', function() {167      formatter.onTestCaseStarted(documentEvent);168      expect(spyFindScenario).toHaveBeenCalledWith(169        formatter.documentsStorage.gherkinDocuments,170        documentEvent.sourceLocation,171      );172    });173    test('should call getUri with uri from event sourceLocation', function() {174      formatter.onTestCaseStarted(documentEvent);175      expect(spyGetUri).toHaveBeenCalledWith(documentEvent.sourceLocation.uri);176    });177    test('should call createTagComparator with pickle tag value', function() {178      formatter.onTestCaseStarted(documentEvent);179      expect(spyCreateTagComparator).toHaveBeenCalledWith(pickleTags[0]);180    });181    test('should call createAttributes with pickleTags', function() {182      formatter.onTestCaseStarted(documentEvent);183      expect(spyCreateAttributes).toHaveBeenCalledWith(pickleTags);184    });185    test('should call startTestItem method from RPClient if isScenarioBasedStatistics is true', function() {186      formatter.isScenarioBasedStatistics = true;187      const itemStartObj = {188        name: 'ft: feature',189        type: 'STEP',190        startTime: mockedDate,191        description: 'feature description',192        attributes: [{ key: 'feature', value: 'value' }],193        retry: false,194      };195      formatter.contextState.context.launchId = 'tempLaunchId';196      const spyStartTestItem = jest.spyOn(formatter.reportportal, 'startTestItem');197      formatter.onTestCaseStarted(documentEvent);198      expect(spyStartTestItem).toHaveBeenCalledWith(itemStartObj, 'tempLaunchId', 'featureId');199    });200    test('should call startTestItem method from RPClient if isScenarioBasedStatistics is false and attemptNumber from event <=2', function() {201      formatter.isScenarioBasedStatistics = false;202      const itemStartObj = {203        name: 'ft: feature',204        type: 'TEST',205        startTime: mockedDate,206        description: 'feature description',207        attributes: [{ key: 'feature', value: 'value' }],208        retry: false,209      };210      formatter.contextState.context.launchId = 'tempLaunchId';211      const spyStartTestItem = jest.spyOn(formatter.reportportal, 'startTestItem');212      formatter.onTestCaseStarted({213        ...documentEvent,214        attemptNumber: 1,215      });216      expect(spyStartTestItem).toHaveBeenCalledWith(itemStartObj, 'tempLaunchId', 'featureId');217    });218    test('should not call startTestItem method from RPClient if isScenarioBasedStatistics is false and attemptNumber from event >=2', function() {219      formatter.isScenarioBasedStatistics = false;220      const spyStartTestItem = jest.spyOn(formatter.reportportal, 'startTestItem');221      formatter.onTestCaseStarted({222        ...documentEvent,223        attemptNumber: 2,224      });225      expect(spyStartTestItem).toHaveBeenCalledTimes(0);226    });227  });228  describe('onTestStepStarted', () => {229    const stepMock = {230      keyword: 'stepExample',231    };232    const stepDefinitionMock = {233      name: 'stepDefinition',234    };235    const event = {236      index: 0,237      testCase: {238        attemptNumber: 1,239      },240    };241    let spyFindStep;242    let spyFindStepDefinition;243    let spyGetStepType;244    beforeAll(() => {245      spyFindStepDefinition = jest246        .spyOn(itemFinders, 'findStepDefinition')247        .mockImplementation(() => stepDefinitionMock);248      spyGetStepType = jest.spyOn(utils, 'getStepType').mockReturnValue('STEP');249    });250    beforeEach(() => {251      spyFindStep = jest252        .spyOn(formatter.contextState, 'findStep')253        .mockImplementation(() => stepMock);254      formatter.contextState.context.stepDefinitions = {255        steps: [256          {257            sourceLocation: {},258          },259        ],260      };261    });262    test('should call findStep function to find step for context', function() {263      formatter.onTestStepStarted(event);264      expect(spyFindStep).toHaveBeenCalledWith(event);265      expect(formatter.contextState.context.step).toEqual(stepMock);266    });267    test('should call findStepDefinition function to find step definition for context', function() {268      formatter.onTestStepStarted(event);269      expect(spyFindStepDefinition).toHaveBeenCalledWith(formatter.contextState.context, event);270      expect(formatter.contextState.context.stepDefinition).toEqual(stepDefinitionMock);271    });272    test('should call getStepType function to get type for step', function() {273      formatter.onTestStepStarted(event);274      expect(spyGetStepType).toHaveBeenCalledWith(stepMock.keyword);275    });276    test('should call startTestItem method from RPClient', function() {277      formatter.contextState.context.launchId = 'launchId';278      formatter.contextState.context.scenarioId = 'scenarioId';279      formatter.isScenarioBasedStatistics = false;280      const itemStartObj = {281        name: stepMock.keyword,282        type: 'STEP',283        startTime: mockedDate,284        description: '',285        hasStats: true,286        retry: false,287      };288      const spyStartTestItem = jest.spyOn(formatter.reportportal, 'startTestItem');289      formatter.onTestStepStarted(event);290      expect(spyStartTestItem).toHaveBeenCalledWith(itemStartObj, 'launchId', 'scenarioId');291      expect(formatter.contextState.context.stepId).toBe('testItemId');292    });293    test('should not call startTestItem method and stop function execution', function() {294      formatter.contextState.context.stepDefinitions = {295        steps: [296          {297            actionLocation: {298              uri: `uri: ${AFTER_HOOK_URI_TO_SKIP}`,299            },300          },301        ],302      };303      const spyStartTestItem = jest.spyOn(formatter.reportportal, 'startTestItem');304      formatter.onTestStepStarted(event);305      expect(spyFindStep).toHaveBeenCalledTimes(0);306      expect(spyFindStepDefinition).toHaveBeenCalledTimes(0);307      expect(spyGetStepType).toHaveBeenCalledTimes(0);308      expect(spyStartTestItem).toHaveBeenCalledTimes(0);309    });310  });311  describe('onTestStepFinished', () => {312    const event = {313      result: {314        status: 'passed',315      },316      testCase: {317        attemptNumber: 1,318        sourceLocation: { uri: 'testCaseUri' },319      },320    };321    let spyGetFileName;322    let spyCountFailedScenarios;323    beforeEach(() => {324      spyGetFileName = jest.spyOn(formatter.contextState, 'getFileName');325      spyCountFailedScenarios = jest326        .spyOn(formatter.contextState, 'countFailedScenarios')327        .mockImplementation(() => {});328      formatter.contextState.context.stepSourceLocation = { sourceLocation: {} };329    });330    test('should call spyGetFileName to get name for screenshot', function() {331      formatter.onTestStepFinished(event);332      expect(spyGetFileName).toHaveBeenCalledTimes(1);333    });334    test('should set passed status for step and scenario in case of passed result status', function() {335      formatter.onTestStepFinished(event);336      expect(formatter.contextState.context.stepStatus).toBe(STATUSES.PASSED);337      expect(formatter.contextState.context.scenarioStatus).toBe(STATUSES.PASSED);338    });339    test('should call sendLog method from RPClient with WARN level in case of pending result status', function() {340      event.result.status = STATUSES.PENDING;341      formatter.contextState.context.stepId = 'stepId';342      formatter.onTestStepFinished(event);343      const spySendLog = jest.spyOn(formatter.reportportal, 'sendLog');344      expect(spySendLog).toHaveBeenCalledWith('stepId', {345        time: mockedDate,346        level: 'WARN',347        message: "This step is marked as 'pending'",348      });349    });350    test('should set not_implemented status for step and failed for scenario in case of pending result status', function() {351      event.result.status = STATUSES.PENDING;352      formatter.contextState.context.stepId = 'stepId';353      formatter.onTestStepFinished(event);354      expect(formatter.contextState.context.stepStatus).toBe(STATUSES.NOT_IMPLEMENTED);355      expect(formatter.contextState.context.scenarioStatus).toBe(STATUSES.FAILED);356      expect(spyCountFailedScenarios).toHaveBeenCalledWith(event.testCase.sourceLocation.uri);357    });358    test('should call sendLog method from RPClient with ERROR level in case of undefined result status', function() {359      event.result.status = STATUSES.UNDEFINED;360      formatter.contextState.context.stepId = 'stepId';361      formatter.onTestStepFinished(event);362      const spySendLog = jest.spyOn(formatter.reportportal, 'sendLog');363      expect(spySendLog).toHaveBeenCalledWith('stepId', {364        time: mockedDate,365        level: 'ERROR',366        message: 'There is no step definition found. Please verify and implement it.',367      });368    });369    test('should set not_found status for step and failed for scenario in case of undefined result status', function() {370      event.result.status = STATUSES.UNDEFINED;371      formatter.contextState.context.stepId = 'stepId';372      formatter.onTestStepFinished(event);373      expect(formatter.contextState.context.stepStatus).toBe(STATUSES.NOT_FOUND);374      expect(formatter.contextState.context.scenarioStatus).toBe(STATUSES.FAILED);375      expect(spyCountFailedScenarios).toHaveBeenCalledWith(event.testCase.sourceLocation.uri);376    });377    test('should call sendLog method from RPClient with ERROR level in case of ambiguous result status', function() {378      event.result.status = STATUSES.AMBIGUOUS;379      formatter.contextState.context.stepId = 'stepId';380      formatter.onTestStepFinished(event);381      const spySendLog = jest.spyOn(formatter.reportportal, 'sendLog');382      expect(spySendLog).toHaveBeenCalledWith('stepId', {383        time: mockedDate,384        level: 'ERROR',385        message: 'There are more than one step implementation. Please verify and reimplement it.',386      });387    });388    test('should set not_found status for step and failed for scenario in case of ambiguous result status', function() {389      event.result.status = STATUSES.AMBIGUOUS;390      formatter.contextState.context.stepId = 'stepId';391      formatter.onTestStepFinished(event);392      expect(formatter.contextState.context.stepStatus).toBe(STATUSES.NOT_FOUND);393      expect(formatter.contextState.context.scenarioStatus).toBe(STATUSES.FAILED);394      expect(spyCountFailedScenarios).toHaveBeenCalledWith(event.testCase.sourceLocation.uri);395    });396    test('should set skipped status for step in case of skipped result status', function() {397      event.result.status = STATUSES.SKIPPED;398      formatter.onTestStepFinished(event);399      expect(formatter.contextState.context.stepStatus).toBe(STATUSES.SKIPPED);400    });401    test('should set skipped status for scenario if it was failed in case of skipped result status', function() {402      event.result.status = STATUSES.SKIPPED;403      formatter.contextState.context.scenarioStatus = STATUSES.FAILED;404      formatter.onTestStepFinished(event);405      expect(formatter.contextState.context.scenarioStatus).toBe(STATUSES.SKIPPED);406    });407    test('should call sendLog method from RPClient with ERROR level in case of failed result status', function() {408      event.result.status = STATUSES.FAILED;409      event.result.exception = 255;410      const stepDefinitionMock = {411        uri: 'stepDefinition',412      };413      formatter.contextState.context.stepDefinition = stepDefinitionMock;414      formatter.contextState.context.stepId = 'stepId';415      formatter.onTestStepFinished(event);416      const spySendLog = jest.spyOn(formatter.reportportal, 'sendLog');417      expect(spySendLog).toHaveBeenCalledWith('stepId', {418        time: mockedDate,419        level: 'ERROR',420        message: `${stepDefinitionMock.uri}\n 255`,421      });422    });423    test('should set failed status for step in case of failed result status', function() {424      event.result.status = STATUSES.FAILED;425      formatter.contextState.context.stepDefinition = {426        uri: 'stepDefinition',427      };428      formatter.onTestStepFinished(event);429      expect(formatter.contextState.context.stepStatus).toBe(STATUSES.FAILED);430      expect(spyCountFailedScenarios).toHaveBeenCalledWith(event.testCase.sourceLocation.uri);431    });432    test('should call finishTestItem method from RPClient', function() {433      event.result.status = STATUSES.PASSED;434      formatter.contextState.context.stepId = 'stepId';435      const itemFinishObj = {436        status: STATUSES.PASSED,437        endTime: mockedDate,438      };439      const spyStartTestItem = jest.spyOn(formatter.reportportal, 'finishTestItem');440      formatter.onTestStepFinished(event);441      expect(spyStartTestItem).toHaveBeenCalledWith('stepId', itemFinishObj);442    });443    test('should call finishTestItem method from RPClient with ab001 issue in case of not_found step status', function() {444      event.result.status = STATUSES.UNDEFINED;445      formatter.contextState.context.stepId = 'stepId';446      const itemFinishObj = {447        status: STATUSES.FAILED,448        endTime: mockedDate,449        issue: {450          issueType: 'ab001',451          comment: 'STEP DEFINITION WAS NOT FOUND',452        },453      };454      const spyStartTestItem = jest.spyOn(formatter.reportportal, 'finishTestItem');455      formatter.onTestStepFinished(event);456      expect(spyStartTestItem).toHaveBeenCalledWith('stepId', itemFinishObj);457    });458    test('should call finishTestItem method from RPClient with ti001 issue in case of not_implemented step status', function() {459      event.result.status = STATUSES.PENDING;460      formatter.contextState.context.stepId = 'stepId';461      const itemFinishObj = {462        status: STATUSES.SKIPPED,463        endTime: mockedDate,464        issue: {465          issueType: 'ti001',466          comment: 'STEP IS PENDING IMPLEMENTATION',467        },468      };469      const spyStartTestItem = jest.spyOn(formatter.reportportal, 'finishTestItem');470      formatter.onTestStepFinished(event);471      expect(spyStartTestItem).toHaveBeenCalledWith('stepId', itemFinishObj);472    });473    test('should not call finishTestItem method and stop function execution', function() {474      formatter.contextState.context.stepSourceLocation = {475        actionLocation: {476          uri: `uri: ${AFTER_HOOK_URI_TO_SKIP}`,477        },478      };479      const spyFinishTestItem = jest.spyOn(formatter.reportportal, 'finishTestItem');480      const spySendLog = jest.spyOn(formatter.reportportal, 'sendLog');481      formatter.onTestStepFinished(event);482      expect(spyGetFileName).toHaveBeenCalledTimes(0);483      expect(spyCountFailedScenarios).toHaveBeenCalledTimes(0);484      expect(spySendLog).toHaveBeenCalledTimes(0);485      expect(spyFinishTestItem).toHaveBeenCalledTimes(0);486    });487  });488  describe('onTestStepAttachment', () => {489    const mockFileObj = {490      level: 'INFO',491      message: 'file',492      data: 'string',493    };494    const event = {495      data: [496        {497          item: 'text',498        },499      ],500    };501    const spyGetJSON = jest.spyOn(utils, 'getJSON');502    let spyGetFileName;503    beforeEach(() => {504      spyGetFileName = jest505        .spyOn(formatter.contextState, 'getFileName')506        .mockImplementation(() => 'fileName');507      formatter.contextState.context.stepStatus = STATUSES.PASSED;508      formatter.contextState.context.stepId = 'stepId';509    });510    test('should call spyGetFileName to get name for file', function() {511      event.media = {512        type: 'text/plain',513      };514      spyGetJSON.mockImplementationOnce(() => mockFileObj);515      formatter.onTestStepAttachment(event);516      expect(spyGetFileName).toHaveBeenCalledTimes(1);517    });518    test('should call sendLog method from RPClient to send log with attachment for text media type', function() {519      event.media = {520        type: 'text/plain',521      };522      spyGetJSON.mockImplementationOnce(() => mockFileObj);523      const request = {524        level: mockFileObj.level,525        message: mockFileObj.message,526        time: mockedDate,527      };528      const spySendLog = jest.spyOn(formatter.reportportal, 'sendLog');529      formatter.onTestStepAttachment(event);530      expect(spySendLog).toHaveBeenCalledWith('stepId', request);531    });532    test('should call sendLog method from RPClient with DEBUG level log in case of invalid json data for text media type', function() {533      event.media = {534        type: 'text/plain',535      };536      spyGetJSON.mockImplementationOnce(() => false);537      const request = {538        level: 'DEBUG',539        message: event.data,540        time: mockedDate,541      };542      const spySendLog = jest.spyOn(formatter.reportportal, 'sendLog');543      formatter.onTestStepAttachment(event);544      expect(spySendLog).toHaveBeenCalledWith('stepId', request);545    });546    test('should call sendLog method from RPClient to send log with attachment for other media type', function() {547      event.media = {548        type: 'other',549      };550      spyGetJSON.mockImplementationOnce(() => mockFileObj);551      const request = {552        level: mockFileObj.level,553        message: mockFileObj.message,554        time: mockedDate,555        file: {556          name: mockFileObj.message,557        },558      };559      const fileObj = {560        name: 'fileName',561        type: 'other',562        content: mockFileObj.data,563      };564      const spySendLog = jest.spyOn(formatter.reportportal, 'sendLog');565      formatter.onTestStepAttachment(event);566      expect(spySendLog).toHaveBeenCalledWith('stepId', request, fileObj);567    });568    test('should call sendLog method from RPClient with default parameters in case of invalid json data for other media type', function() {569      event.media = {570        type: 'other',571      };572      spyGetJSON.mockImplementationOnce(() => false);573      const request = {574        level: 'DEBUG',575        message: 'fileName',576        time: mockedDate,577        file: {578          name: 'fileName',579        },580      };581      const fileObj = {582        name: 'fileName',583        type: 'other',584        content: event.data,585      };586      const spySendLog = jest.spyOn(formatter.reportportal, 'sendLog');587      formatter.onTestStepAttachment(event);588      expect(spySendLog).toHaveBeenCalledWith('stepId', request, fileObj);589    });590  });591  describe('onTestCaseFinished', () => {592    const itemUri = 'itemUri';593    const event = {594      sourceLocation: {595        uri: itemUri,596      },597      result: {598        status: STATUSES.PASSED,599      },600    };601    let spyFinishTestItem;602    beforeEach(() => {603      spyFinishTestItem = jest.spyOn(formatter.reportportal, 'finishTestItem');604      formatter.isScenarioBasedStatistics = false;605      formatter.contextState.context.scenarioId = 'scenarioId';606      formatter.contextState.context.scenariosCount[itemUri] = {607        done: 0,608        total: 2,609      };610      formatter.documentsStorage.pickleDocuments[itemUri] = {611        featureId: 'featureId',612      };613    });614    test('should call finishTestItem method from RPClient to finish test item', function() {615      formatter.onTestCaseFinished(event);616      const itemFinishObj = {617        status: STATUSES.PASSED,618        endTime: mockedDate,619      };620      expect(spyFinishTestItem).toHaveBeenCalledWith('scenarioId', itemFinishObj);621      expect(formatter.contextState.context.scenarioStatus).toBe(STATUSES.FAILED);622      expect(formatter.contextState.context.scenarioId).toBe(null);623    });624    test('should call finishTestItem method from RPClient and finish test item with failed status in case of result status not passed', function() {625      event.result.status = STATUSES.SKIPPED;626      formatter.onTestCaseFinished(event);627      const itemFinishObj = {628        status: STATUSES.FAILED,629        endTime: mockedDate,630      };631      expect(spyFinishTestItem).toHaveBeenCalledWith('scenarioId', itemFinishObj);632      expect(formatter.contextState.context.scenarioStatus).toBe(STATUSES.FAILED);633      expect(formatter.contextState.context.scenarioId).toBe(null);634    });635    test('should increase scenariosCount done in context', function() {636      event.result.status = STATUSES.PASSED;637      formatter.onTestCaseFinished(event);638      expect(formatter.contextState.context.scenariosCount[itemUri].done).toBe(1);639    });640    test('should call finishTestItem method from RPClient twice in case of finishing the item from suite', function() {641      formatter.contextState.context.scenariosCount[itemUri].total = 1;642      formatter.contextState.context.failedScenarios[itemUri] = 0;643      event.result.status = STATUSES.PASSED;644      formatter.onTestCaseFinished(event);645      const finishItemObj = {646        status: STATUSES.PASSED,647        endTime: mockedDate,648      };649      expect(spyFinishTestItem).toHaveBeenCalledTimes(2);650      expect(spyFinishTestItem).toHaveBeenNthCalledWith(2, 'featureId', finishItemObj);651    });652    test('should call finishTestItem method from RPClient second time with failed status in case of failed scenarios in suite', function() {653      formatter.contextState.context.scenariosCount[itemUri].total = 1;654      formatter.contextState.context.failedScenarios[itemUri] = 1;655      event.result.status = STATUSES.PASSED;656      formatter.onTestCaseFinished(event);657      const finishItemObj = {658        status: STATUSES.FAILED,659        endTime: mockedDate,660      };661      expect(spyFinishTestItem).toHaveBeenCalledTimes(2);662      expect(spyFinishTestItem).toHaveBeenNthCalledWith(2, 'featureId', finishItemObj);663    });664    test('should not call finishTestItem method and stop function execution', function() {665      formatter.isScenarioBasedStatistics = false;666      event.result.retried = true;667      formatter.onTestCaseFinished(event);668      expect(spyFinishTestItem).toHaveBeenCalledTimes(0);669    });670  });671  describe('onTestRunFinished', () => {672    let spyGetPromiseFinishAllItems;673    let spyFinishLaunch;674    beforeEach(() => {675      spyGetPromiseFinishAllItems = jest.spyOn(formatter.reportportal, 'getPromiseFinishAllItems');676      spyFinishLaunch = jest.spyOn(formatter.reportportal, 'finishLaunch');677    });678    test('should call getPromiseFinishAllItems method from RPClient & should not call finishLaunch method for empty launch id', function() {679      formatter.contextState.context.launchId = null;680      formatter.onTestRunFinished();681      expect(spyGetPromiseFinishAllItems).toHaveBeenCalledWith(null);682      expect(spyFinishLaunch).toHaveBeenCalledTimes(0);683    });684    test('should call getPromiseFinishAllItems method from RPClient and should finish launch with corresponding id', async function() {685      formatter.contextState.context.launchId = 'launchId';686      await formatter.onTestRunFinished();687      expect(spyGetPromiseFinishAllItems).toHaveBeenCalledWith('launchId');688      expect(spyFinishLaunch).toHaveBeenCalledWith('launchId', { endTime: mockedDate });689    });690    test('should call resetContext method from context after finishing launch', async function() {691      formatter.contextState.context.launchId = 'launchId';692      const spyResetContext = jest.spyOn(formatter.contextState, 'resetContext');693      await formatter.onTestRunFinished();694      expect(spyResetContext).toHaveBeenCalledTimes(1);695    });696  });...

Full Screen

Full Screen

pickle_compiler.js

Source:pickle_compiler.js Github

copy

Full Screen

...48    steps = steps.concat(pickleSteps(scenario.steps))49    var tags = [].concat(featureTags).concat(scenario.tags);50    var pickle = m.Pickle.fromObject({51      uri: uri,52      tags: pickleTags(tags),53      name: scenario.name,54      language: language,55      locations: [scenario.location],56      steps: steps57    })58    pickles.push(pickle);59  }60  function compileScenarioOutline(featureTags, backgroundSteps, scenario, language, pickles, uri) {61    for (var i in scenario.examples) {62      var examples = scenario.examples[i]63      if (!examples.tableHeader) continue64      var variableCells = examples.tableHeader.cells;65      examples.tableBody.forEach(function (values) {66        var valueCells = values.cells;67        var steps = scenario.steps.length === 0 ? [] : [].concat(backgroundSteps);68        var tags = [].concat(featureTags).concat(scenario.tags).concat(examples.tags);69        scenario.steps.forEach(function (scenarioOutlineStep) {70          var pickleStepOb = pickleStepObject(scenarioOutlineStep, variableCells, valueCells)71          pickleStepOb.locations.push(values.location)72          var pickleStep = m.PickleStep.fromObject(pickleStepOb)73          steps.push(pickleStep);74        });75        var pickle = m.Pickle.fromObject({76          uri: uri,77          name: interpolate(scenario.name, variableCells, valueCells),78          language: language,79          steps: steps,80          tags: pickleTags(tags),81          locations: [82            scenario.location,83            values.location84          ]85        })86        pickles.push(pickle);87      });88    }89  }90  function interpolate(name, variableCells, valueCells) {91    variableCells.forEach(function (variableCell, n) {92      var valueCell = valueCells[n];93      var search = new RegExp('<' + variableCell.value + '>', 'g');94      // JS Specific - dollar sign needs to be escaped with another dollar sign95      // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_string_as_a_parameter96      var replacement = valueCell.value.replace(new RegExp('\\$', 'g'), '$$$$')97      name = name.replace(search, replacement);98    });99    return name;100  }101  function pickleSteps(steps) {102    return steps.map(function (step) {103      return m.PickleStep.fromObject(pickleStepObject(step, [], []))104    });105  }106  function pickleStepObject(step, variableCells, valueCells) {107    var stepText = interpolate(step.text, variableCells, valueCells);108    var ob = {109      text: stepText,110      locations: [pickleStepLocation(step)]111    }112    if (step.dataTable) {113      ob.dataTable = pickleDataTable(step.dataTable, variableCells, valueCells)114    }115    if (step.docString) {116      ob.docString = pickleDocString(step.docString, variableCells, valueCells)117    }118    return ob119  }120  function pickleDocString(docString, variableCells, valueCells) {121    return m.PickleDocString.fromObject({122      location: docString.location,123      content: interpolate(docString.content, variableCells, valueCells),124      contentType: docString.contentType ? interpolate(docString.contentType, variableCells, valueCells) : null125    })126  }127  function pickleDataTable(dataTable, variableCells, valueCells) {128    return m.PickleTable.fromObject({129      rows: dataTable.rows.map(function (row) {130        return m.PickleTableRow.fromObject({131          cells: row.cells.map(function (cell) {132            return m.PickleTableCell.fromObject({133              location: cell.location,134              value: interpolate(cell.value, variableCells, valueCells)135            });136          })137        })138      })139    })140  }141  function pickleStepLocation(step) {142    return m.Location.fromObject({143      line: step.location.line,144      column: step.location.column + (step.keyword ? countSymbols(step.keyword) : 0)145    })146  }147  function pickleTags(tags) {148    return tags.map(function (tag) {149      return pickleTag(tag);150    });151  }152  function pickleTag(tag) {153    return m.PickleTag.fromObject({154      name: tag.name,155      location: tag.location156    });157  }158}...

Full Screen

Full Screen

compiler.js

Source:compiler.js Github

copy

Full Screen

...25    scenario.steps.forEach(function (step) {26      steps.push(pickleStep(step));27    });28    var pickle = {29      tags: pickleTags(tags),30      name: scenario.name,31      language: language,32      locations: [pickleLocation(scenario.location)],33      steps: steps34    };35    pickles.push(pickle);36  }37  function compileScenarioOutline(featureTags, backgroundSteps, scenarioOutline, language, pickles) {38    if (scenarioOutline.steps.length == 0) return;39    scenarioOutline.examples.filter(function(e) { return e.tableHeader != undefined; }).forEach(function (examples) {40      var variableCells = examples.tableHeader.cells;41      examples.tableBody.forEach(function (values) {42        var valueCells = values.cells;43        var steps = [].concat(backgroundSteps);44        var tags = [].concat(featureTags).concat(scenarioOutline.tags).concat(examples.tags);45        scenarioOutline.steps.forEach(function (scenarioOutlineStep) {46          var stepText = interpolate(scenarioOutlineStep.text, variableCells, valueCells);47          var args = createPickleArguments(scenarioOutlineStep.argument, variableCells, valueCells);48          var pickleStep = {49            text: stepText,50            arguments: args,51            locations: [52              pickleLocation(values.location),53              pickleStepLocation(scenarioOutlineStep)54            ]55          };56          steps.push(pickleStep);57        });58        var pickle = {59          name: interpolate(scenarioOutline.name, variableCells, valueCells),60          language: language,61          steps: steps,62          tags: pickleTags(tags),63          locations: [64            pickleLocation(values.location),65            pickleLocation(scenarioOutline.location)66          ]67        };68        pickles.push(pickle);69      });70    });71  }72  function createPickleArguments(argument, variableCells, valueCells) {73    var result = [];74    if (!argument) return result;75    if (argument.type === 'DataTable') {76      var table = {77        rows: argument.rows.map(function (row) {78          return {79            cells: row.cells.map(function (cell) {80              return {81                location: pickleLocation(cell.location),82                value: interpolate(cell.value, variableCells, valueCells)83              };84            })85          };86        })87      };88      result.push(table);89    } else if (argument.type === 'DocString') {90      var docString = {91        location: pickleLocation(argument.location),92        content: interpolate(argument.content, variableCells, valueCells)93      };94      result.push(docString);95    } else {96      throw Error('Internal error');97    }98    return result;99  }100  function interpolate(name, variableCells, valueCells) {101    variableCells.forEach(function (variableCell, n) {102      var valueCell = valueCells[n];103      var search = new RegExp('<' + variableCell.value + '>', 'g');104      name = name.replace(search, valueCell.value);105    });106    return name;107  }108  function pickleSteps(scenarioDefinition) {109    return scenarioDefinition.steps.map(function (step) {110      return pickleStep(step);111    });112  }113  function pickleStep(step) {114    return {115      text: step.text,116      arguments: createPickleArguments(step.argument, [], []),117      locations: [pickleStepLocation(step)]118    }119  }120  function pickleStepLocation(step) {121    return {122      line: step.location.line,123      column: step.location.column + (step.keyword ? countSymbols(step.keyword) : 0)124    };125  }126  function pickleLocation(location) {127    return {128      line: location.line,129      column: location.column130    }131  }132  function pickleTags(tags) {133    return tags.map(function (tag) {134      return pickleTag(tag);135    });136  }137  function pickleTag(tag) {138    return {139      name: tag.name,140      location: pickleLocation(tag.location)141    };142  }143}...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var gherkin = require('cucumber-gherkin');2var fs = require('fs');3var feature = fs.readFileSync('test.feature').toString();4var options = {5};6gherkin.fromSources([feature], options, function(err, res) {7  console.log(res[0].pickles[0].tags);8});9[ { location: { line: 1, column: 1 },10    astNodeIds: [ '0' ] } ]11[ { location: { line: 1, column: 1 },12    astNodeIds: [ '0' ] },13  { location: { line: 1, column: 1 },14    astNodeIds: [ '0' ] } ]15[ { location: { line: 1, column: 1 },16    astNodeIds: [ '0' ] },17  { location: { line: 1, column: 1 },18    astNodeIds: [ '0' ] },19  { location: { line: 1, column: 1 },20    astNodeIds: [ '0' ] } ]21[ { location: { line: 1, column: 1 },22    astNodeIds: [ '0' ] },23  { location: { line: 1, column: 1 },24    astNodeIds: [ '0' ] },25  { location: { line: 1, column: 1 },26    astNodeIds: [ '0' ] },27  { location: { line: 1, column: 1 },

Full Screen

Using AI Code Generation

copy

Full Screen

1var gherkin = require("cucumber-gherkin");2var fs = require("fs");3var gherkinDocument = gherkin.parse(fs.readFileSync("test.feature", "utf-8"));4var pickle = gherkin.pickles(gherkinDocument)[0];5console.log(pickle);6{ name: 'Test scenario',7   [ { keyword: 'Given ',8       locations: [Object] } ],9  location: { line: 2, column: 3 } }10var gherkin = require("cucumber-gherkin");11var fs = require("fs");12var gherkinDocument = gherkin.parse(fs.readFileSync("test.feature", "utf-8"));13var pickle = gherkin.pickles(gherkinDocument)[0];14console.log(pickle);15{ name: 'Test scenario',16   [ { keyword: 'Given ',17       locations: [Object] } ],18  location: { line: 2, column: 3 } }19var gherkin = require("cucumber-gherkin");20var fs = require("fs");21var gherkinDocument = gherkin.parse(fs.readFileSync("test.feature", "

Full Screen

Using AI Code Generation

copy

Full Screen

1var gherkin = require('gherkin');2var parser = new gherkin.Parser();3var ast = parser.parse("Feature: test4Then I should see something");5console.log(gherkin.PickleCompiler.compile(ast));6[ { name: 'test',7     [ { text: 'Given I am a user', arguments: [] },8       { text: 'When I do something', arguments: [] },9       { text: 'Then I should see something', arguments: [] } ],10    tags: [] } ]11var gherkin = require('gherkin');12var parser = new gherkin.Parser();13var ast = parser.parse("Feature: test14Then I should see something");15console.log(gherkin.PickleCompiler.compile(ast));16[ { name: 'test',17     [ { text: 'Given I am a user', arguments: [] },18       { text: 'When I do something', arguments: [] },19       { text: 'Then I should see something', arguments: [] } ],20    tags: [ '@tag1', '@tag2' ] } ]21var gherkin = require('gherkin');22var parser = new gherkin.Parser();23var ast = parser.parse("Feature: test24Then I should see something");25console.log(gherkin.PickleCompiler.compile(ast));26[ { name: 'test',27     [ { text: 'Given I am a user', arguments: [] },28       { text: 'When I do something', arguments: [] },29       { text: 'Then I should see something', arguments: [] } ],30    tags: [ '@tag1', '@tag2' ] },31  { name: 'test2',

Full Screen

Using AI Code Generation

copy

Full Screen

1var gherkin = require('cucumber-gherkin');2gherkin.fromPaths(['features/*.feature'], function(err, data) {3  console.log(data);4});5var gherkin = require('cucumber-gherkin');6gherkin.fromPaths(['features/*.feature'], function(err, data) {7  console.log(data);8  var tags = [];9  for (var i = 0; i < data.length; i++) {10    for (var j = 0; j < data[i].pickles.length; j++) {11      for (var k = 0; k < data[i].pickles[j].tags.length; k++) {12        tags.push(data[i].pickles[j].tags[k].name);13      }14    }15  }16  console.log(tags);17});18var gherkin = require('cucumber-gherkin');19gherkin.fromPaths(['features/*.feature'], function(err, data) {20  console.log(data);

Full Screen

Using AI Code Generation

copy

Full Screen

1var cucumberGherkin = require('cucumber-gherkin');2var fs = require('fs');3var featureFile = "features/feature.feature";4var tags = cucumberGherkin.pickleTags(featureFile);5for (var i = 0; i < tags.length; i++) {6    console.log(tags[i].name);7    console.log(tags[i].line);8}9fs.readFile(featureFile, 'utf8', function (err, data) {10    if (err) {11        return console.log(err);12    }13    var result = data.replace(/@/g, "");14    fs.writeFile(featureFile, result, 'utf8', function (err) {15        if (err) return console.log(err);16    });17});

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