How to use pickleStep method in Cucumber-gherkin

Best JavaScript code snippet using cucumber-gherkin

cuebot-formatter.js

Source:cuebot-formatter.js Github

copy

Full Screen

1/*2 * Copyright 2020 Jonathan L. Magaru <jonathan.magaru.code@gmail.com>3 * Licensed under the MIT license. See LICENSE.4 *5 * Cuebot - Formatter for CucumberJS6 */7"use strict";8const { JsonFormatter } = require("cucumber");9const Table = require("cli-table3");10const colors = require("chalk");11const readline = require("readline");12const ora = require("ora");13const prettyTime = require("pretty-ms");14class CuebotAPIFormatter extends JsonFormatter {15 constructor(options) {16 super(options);17 this.inCi = true;18 // get the JSON data from JsonFormatter19 this.spinner = new ora({20 spinner: "dots",21 isEnabled: !this.inCi,22 });23 this.spinner._passed = this.spinner.succeed;24 this.spinner._failed = this.spinner.fail;25 this.spinner._skipped = this.spinner.info;26 this.spinner._pending = this.spinner.warn;27 this.spinner._undefined = this.spinner.warn;28 this.spinner._ambiguous = this.spinner.warn;29 this.logFn = this.log;30 this.log = (data) => {31 const featuresSummaryTable = new Table({32 head: ["Features", "Result %", "Scenarios", "Steps"],33 colAligns: [null, "right", "right", "right"],34 style: {35 head: [],36 border: [],37 },38 });39 const detailsSummaryTable = new Table({40 head: [41 "Features / Scenarios",42 "Result",43 "Steps",44 "Passed",45 "Failed",46 "Skipped",47 "Pending",48 "Ambiguous",49 "Unknown",50 ],51 colAligns: [52 null,53 null,54 "right",55 "right",56 "right",57 "right",58 "right",59 "right",60 "right",61 ],62 style: {63 head: [],64 border: [],65 },66 });67 // eslint-disable-next-line no-unused-vars68 JSON.parse(data).forEach((feature) => {69 let totals = { steps: 0, passed: 0 };70 detailsSummaryTable.push([71 { colSpan: 9, content: colors.blue(feature.name) },72 ]);73 feature.elements.forEach((scenario) => {74 let stats = scenario.steps.reduce(75 (st, step) => {76 let is_ = (keyword) =>77 step.hidden ? 0 : step.result.status == keyword ? 1 : 0;78 st.passed += is_("passed");79 st.failed += is_("failed");80 st.skipped += is_("skipped");81 st.pending += is_("pending");82 st.undf += is_("undefined");83 st.ambiguous += is_("ambiguous");84 return st;85 },86 {87 passed: 0,88 failed: 0,89 skipped: 0,90 pending: 0,91 undf: 0,92 ambiguous: 0,93 }94 );95 let _steps = Object.entries(stats).reduce(96 (sum, stat) => sum + stat[1],97 098 );99 let isPassed = (stats) => {100 return (101 stats.passed > 0 &&102 Object.entries(stats)103 .filter((stat) => stat[0] != "passed")104 .reduce((sum, stat) => sum + stat[1], 0) == 0105 );106 };107 detailsSummaryTable.push([108 " " + scenario.name,109 _steps > 0110 ? isPassed(stats)111 ? colors.green("✔ Passed")112 : colors.red("✖ Failed")113 : colors.yellow("---"),114 _steps,115 stats.passed,116 this.condColor((value) => value > 0, stats.failed, {117 true: colors.red,118 false: colors.white,119 }),120 this.condColor((value) => value > 0, stats.skipped, {121 true: colors.cyan,122 false: colors.white,123 }),124 this.condColor((value) => value > 0, stats.pending, {125 true: colors.yellow,126 false: colors.white,127 }),128 this.condColor((value) => value > 0, stats.ambiguous, {129 true: colors.gray,130 false: colors.white,131 }),132 this.condColor((value) => value > 0, stats.undf, {133 true: colors.gray,134 false: colors.white,135 }),136 ]);137 totals.steps += _steps;138 totals.passed += stats.passed;139 });140 featuresSummaryTable.push([141 feature.name,142 totals.steps > 0143 ? this.condColor(144 (value) => (value >= 100 ? 0 : value < 50 ? 1 : 2),145 ((totals.passed / totals.steps) * 100).toFixed(2),146 { 0: colors.green, 1: colors.red, 2: colors.yellow }147 )148 : colors.yellow("---"),149 feature.elements.length,150 totals.steps,151 ]);152 });153 this.logFn(154 `\n${colors.green(155 "Test Result Summary"156 )}\n${featuresSummaryTable.toString()} \n\n${detailsSummaryTable.toString()} \n`157 );158 };159 options.eventBroadcaster.on("test-case-started", ({ sourceLocation }) => {160 const {161 gherkinDocument,162 pickle,163 } = options.eventDataCollector.getTestCaseData(sourceLocation);164 readline.clearLine();165 readline.cursorTo(0);166 const { feature } = gherkinDocument;167 this.logFn(168 `\n${colors.magenta.bold(feature.keyword)}: ${colors.bgBlue(169 feature.name170 )} > ${colors.bold.underline(pickle.name)} \n`171 );172 });173 options.eventBroadcaster.on("test-step-started", ({ testCase, index }) => {174 if (index == 0) return;175 const {176 pickleStep,177 gherkinKeyword,178 } = this.eventDataCollector.getTestStepData({ testCase, index });179 if (pickleStep) {180 if (!this.inCi) {181 this.spinner.text = `\t ${colors.yellow(gherkinKeyword)}${182 pickleStep.text183 }`;184 this.spinner.start();185 }186 }187 });188 options.eventBroadcaster.on(189 "test-step-finished",190 ({ testCase, index, result }) => {191 if (index == 0) return;192 const {193 pickleStep,194 gherkinKeyword,195 } = this.eventDataCollector.getTestStepData({ testCase, index });196 if (pickleStep) {197 let message = `${this.resolveStatus(result.status)} - ${colors.yellow(198 gherkinKeyword199 )}${this.sanitize(pickleStep.text, true)}${this.displayDuration(200 result201 )}`;202 if (result.status == "failed") {203 try {204 let errors = JSON.parse(result.exception.message);205 message += this.displayJsonErrorBlock(errors);206 } catch (e) {207 message += `\n\t - ${colors.red(result.exception.message)}`;208 }209 }210 this.spinner["_" + result.status](message);211 if (pickleStep.arguments.length > 0) {212 let content = pickleStep.arguments[0].content;213 if (Utils.isJSON(content)) {214 content = JSON.stringify(215 this.sanitizeJson(JSON.parse(content), true),216 null,217 4218 );219 content =220 "\t" + content.replace(new RegExp(/\n/, "g"), "\n\t") + "\n";221 } else {222 const contentTable = new Table({223 colWidths: [20, 60],224 head: pickleStep.arguments[0].rows[0].cells.map((v) => v.value),225 xchars: {226 top: "═",227 "top-mid": "╤",228 "top-left": "\t╔",229 "top-right": "╗",230 bottom: "═",231 "bottom-mid": "╧",232 "bottom-left": "\t╚",233 "bottom-right": "╝",234 left: "\t║",235 "left-mid": "\t╟",236 mid: "─",237 "mid-mid": "┼",238 right: "║",239 "right-mid": "╢",240 middle: "│",241 },242 });243 pickleStep.arguments[0].rows.forEach((value, index) => {244 if (index > 0) {245 contentTable.push(246 value.cells.map((v) =>247 Store.sanitize(v.value, true).substring(0, 50)248 )249 );250 }251 });252 content = contentTable.toString() + "\n";253 }254 if (!this.inCi) this.logFn(colors.gray(content));255 }256 }257 }258 );259 options.eventBroadcaster.on("test-run-started", () => {260 this.logFn(`${colors.green("Cuebot-mobile")} Test Run \n`);261 });262 options.eventBroadcaster.on("test-run-finished", () => {263 if (!this.inCi) this.displayNetworkStatistics();264 });265 }266 displayNetworkStatistics() {267 const networkSummaryTable = new Table({268 head: ["Domain / Path", "Count", "Average", "Min", "Max", "Error Rate %"],269 colAligns: ["left", "right", "right", "right", "right", "right"],270 style: {271 head: [],272 border: [],273 },274 });275 Object.entries(this.stats()).forEach((e) => {276 networkSummaryTable.push([277 { colSpan: 6, content: colors.blue.bold(e[0]) },278 ]);279 Object.entries(e[1]).forEach((p) => {280 networkSummaryTable.push([281 ` ${p[0]}`,282 p[1].count,283 prettyTime(p[1].avg),284 prettyTime(p[1].min),285 prettyTime(p[1].max),286 this.condColor((value) => value > 0, p[1].errors.toFixed(1), {287 true: colors.red,288 false: colors.white,289 }),290 ]);291 });292 });293 this.logFn(`\n${networkSummaryTable.toString()} \n\n`);294 }295 displayJsonErrorBlock(errors) {296 let message = [];297 errors.forEach((error) => {298 let jsonResponse = JSON.stringify(299 Store.resolve(`__response-${error.source}`),300 null,301 4302 ).split("\n");303 let lineColDetails = error.lineNumber ? `line:${error.lineNumber}` : "";304 message.push(305 colors.cyan(306 `\n\n\treports/snapshots/${error.source}.json ${lineColDetails}`307 )308 );309 let dataPathMessage = error.dataPath ? ` at ${error.dataPath} ` : " ";310 message.push(311 "\n\t" +312 colors.red.underline(313 `${error.message}${dataPathMessage}based on ${error.schemaPath}`314 )315 );316 if (error.lineNumber) {317 for (let j = error.lineNumber - 1; j <= error.lineNumber + 1; j++) {318 let lineSource = jsonResponse[j - 1];319 if (j == error.lineNumber) {320 message.push(colors.red(`\n\t ${j}\t${lineSource}`));321 } else {322 message.push(colors.gray(`\n\t ${j}\t${lineSource}`));323 }324 }325 }326 });327 return message.join("");328 }329 condColor(check, value, lookups) {330 return lookups[check(value)](value);331 }332 resolveStatus(status) {333 const statuses = {334 passed: colors.green(" Passed"),335 skipped: colors.blue(" Skipped"),336 failed: colors.red(" Failed"),337 pending: colors.yellow(" Pending"),338 ambiguous: colors.red(" Ambiguous"),339 undefined: colors.gray(" Undefined"),340 };341 return statuses[status];342 }343 displayDuration(result) {344 return process.env.AUTOKIN_TIME == "true" && result.duration345 ? ` (${prettyTime(result.duration)})`346 : "";347 }348 sanitizeJson(obj, fromCache = false) {349 for (var p in obj) {350 if (typeof obj[p] == "object") {351 obj[p] = this.sanitizeJson(obj[p], fromCache);352 } else if (typeof obj[p] == "string") {353 obj[p] = this.sanitize(obj[p], fromCache);354 }355 }356 return obj;357 }358 sanitize(pickle, fromCache = false) {359 return this.interpolateValues(pickle, this.storage, fromCache);360 }361 interpolateValues(pickle, variables, fromCache = false) {362 return pickle.replace(new RegExp("{([^{]+)}", "g"), (match, varName) => {363 if (varName.startsWith("generate:")) {364 return this.generate(varName, fromCache);365 } else if (varName.startsWith("parse:")) {366 return this.parse(varName, fromCache);367 }368 return variables.hasOwnProperty(varName)369 ? variables[varName]370 : "{" + varName + "}";371 });372 }373 stats() {374 let measurements = {};375 return measurements;376 }377}...

Full Screen

Full Screen

scenarios.js

Source:scenarios.js Github

copy

Full Screen

1/** Module for cucumber-junit-formatter before cucumber 6.0.0 */2"use strict;";3const {formatterHelpers} = require('cucumber');4const {createProperty,convertNameToId}=require("../util");5// In cucumber 6.0+ duration in nanoseconds, not milliseconds6const MULTIPLIER=(require("cucumber/lib/time").MILLISECONDS_IN_NANOSECOND||1); // eslint-disable-line global-require7/**8* Create failure tag definition9* @param {String} message failure message10* @return {Object} failure tag 11*/12const createFailure=(message)=>{13 return {14 failure: [15 { _attr: { message: message.split("\n").shift() } },16 message17 ]18 };19},20/**21* Create failure or error tag22* @param {String} type tag name23* @param {Error} exception exception24* @return {Object} generated tag25*/26createFailureOrError=(type,exception)=>{27 let {name}=exception,28 ret ={};29 ret[type]=[30 { _attr: { message: name } },31 formatterHelpers.formatError(exception)32 ];33 return ret;34};35module.exports={36 scenarioAsSuite:(options,result)=>{return ({sourceLocation})=>{ 37 const { gherkinDocument, pickle, testCase } = options.eventDataCollector.getTestCaseData(sourceLocation);38 let testSuiteId=`${convertNameToId(gherkinDocument.feature.name)};${convertNameToId(pickle.name)}`;39 let attr={name:testSuiteId,tests:0,failures:0,skipped:0,errors:0,time:testCase.result.duration||0},40 testSuite=[{_attr:attr}];41 42 if (options.withPackage) {43 attr.package=convertNameToId(pickle.name);44 }45 46 if (pickle.tags.length) {47 testSuite.push({properties:pickle.tags.map(tag=>createProperty("tag",tag.name))});48 }49 50 testCase.steps.forEach((step,index)=>{51 const {gherkinKeyword, pickleStep } = options.eventDataCollector.getTestStepData({testCase:testCase,index:index});52 if (gherkinKeyword || (step.result && step.result.status==='failed')) {53 let result=step.result || {};54 let testCaseId=convertNameToId(gherkinKeyword?pickleStep.text:`${pickle.name} ${index?'after':'before'}`);55 let testCase=[56 {57 _attr:{58 classname:testCaseId,59 name:gherkinKeyword?pickleStep.text:(pickle.name+(index?' after':' before')),60 time:((result.duration || 0)/(1000*MULTIPLIER)).toFixed(3)61 }62 }63 ];64 switch (result.status) {65 case 'passed':66 break;67 case 'failed':68 testCase.push(createFailureOrError(gherkinKeyword?"failure":"error",result.exception));69 if (gherkinKeyword) {70 attr.failures+=1;71 }72 else {73 attr.errors+=1;74 }75 break;76 case 'pending':77 case 'undefined':78 testCase.push(createFailure(result.status === 'pending' ? 'Pending' 79 : `Undefined step. Implement with the following snippet:\n ${gherkinKeyword.trim()}(/^${pickleStep.text}$/, function(callback) {\n // Write code here that turns the phrase above into concrete actions\n callback(null, 'pending');\n });`80 ));81 attr.failures+=1;82 break;83 case 'skipped':84 testCase.push({skipped: []});85 attr.skipped+=1;86 break;87 case 'ambiguous':88 testCase.push(createFailureOrError("error",result.exception));89 attr.errors+=1;90 break;91 default:92 break;93 // testCase.push(createFailure(`Unknown status - ${step.result.status}`));94 }95 attr.tests+=1;96 testSuite.push({testcase:testCase});97 }98 });99 result.push({testsuite:testSuite});100 101 };102 },103 scenarioAsStep:(options,result)=>{return ({sourceLocation})=>{ 104 const { gherkinDocument, pickle, testCase } = options.eventDataCollector.getTestCaseData(sourceLocation);105 let testSuiteId=`${convertNameToId(gherkinDocument.feature.name)}`,106 testCaseId=`${convertNameToId(pickle.name)}`;107 let attr,testSuite;108 if (result.length && result[result.length-1].testsuite[0]._attr.name===testSuiteId) {109 testSuite=result[result.length-1].testsuite;110 attr=testSuite[0]._attr;111 }112 else {113 attr={name:testSuiteId,tests:0,failures:0,skipped:0,errors:0,time:0};114 testSuite=[{_attr:attr}];115 result.push({testsuite:testSuite});116 }117 attr.time+=testCase.result.duration;118 attr.tests+=1;119 let testCaseTag=[120 {121 _attr:{122 classname:testCaseId,123 name:pickle.name,124 time:((testCase.result.duration ||0)/(1000*MULTIPLIER)).toFixed(3)125 }126 }127 ];128 129 if (pickle.tags.length && options.propertiesInTestcase) {130 testCaseTag.push({properties:pickle.tags.map(tag=>createProperty("tag",tag.name))});131 }132 133 testCase.steps.every((step,index)=>{134 const {gherkinKeyword, pickleStep } = options.eventDataCollector.getTestStepData({testCase:testCase,index:index});135 if (gherkinKeyword || (step.result && step.result.status==='failed')) {136 let result=step.result || {};137 switch (result.status) {138 case 'passed':139 break;140 case 'failed':141 testCaseTag.push(createFailureOrError(gherkinKeyword?"failure":"error",result.exception));142 attr[gherkinKeyword?"failures":"errors"]+=1;143 return false;144 case 'pending':145 case 'undefined':146 testCaseTag.push(createFailure(result.status === 'pending' ? 'Pending' 147 : `Undefined step. Implement with the following snippet:\n ${gherkinKeyword.trim()}(/^${pickleStep.text}$/, function(callback) {\n // Write code here that turns the phrase above into concrete actions\n callback(null, 'pending');\n });`148 ));149 attr.failures+=1;150 return false;151 case 'skipped':152 testCaseTag.push({skipped: []});153 attr.skipped+=1;154 return false;155 case 'ambiguous':156 testCaseTag.push(createFailureOrError("error",result.exception));157 attr.errors+=1;158 return false;159 default:160 break;161 // testCase.push(createFailure(`Unknown status - ${step.result.status}`));162 }163 }164 return true;165 });166 testSuite.push({testcase:testCaseTag});167 };168 }169 ...

Full Screen

Full Screen

compiler.js

Source:compiler.js Github

copy

Full Screen

...21 function compileScenario(featureTags, backgroundSteps, scenario, language, pickles) {22 var steps = scenario.steps.length == 0 ? [] : [].concat(backgroundSteps);23 var tags = [].concat(featureTags).concat(scenario.tags);24 scenario.steps.forEach(function (step) {25 steps.push(pickleStep(step));26 });27 var pickle = {28 tags: pickleTags(tags),29 name: scenario.name,30 language: language,31 locations: [pickleLocation(scenario.location)],32 steps: steps33 };34 pickles.push(pickle);35 }36 function compileScenarioOutline(featureTags, backgroundSteps, scenarioOutline, language, pickles) {37 scenarioOutline.examples.filter(function(e) { return e.tableHeader != undefined; }).forEach(function (examples) {38 var variableCells = examples.tableHeader.cells;39 examples.tableBody.forEach(function (values) {40 var valueCells = values.cells;41 var steps = scenarioOutline.steps.length == 0 ? [] : [].concat(backgroundSteps);42 var tags = [].concat(featureTags).concat(scenarioOutline.tags).concat(examples.tags);43 scenarioOutline.steps.forEach(function (scenarioOutlineStep) {44 var stepText = interpolate(scenarioOutlineStep.text, variableCells, valueCells);45 var args = createPickleArguments(scenarioOutlineStep.argument, variableCells, valueCells);46 var pickleStep = {47 text: stepText,48 arguments: args,49 locations: [50 pickleLocation(values.location),51 pickleStepLocation(scenarioOutlineStep)52 ]53 };54 steps.push(pickleStep);55 });56 var pickle = {57 name: interpolate(scenarioOutline.name, variableCells, valueCells),58 language: language,59 steps: steps,60 tags: pickleTags(tags),61 locations: [62 pickleLocation(values.location),63 pickleLocation(scenarioOutline.location)64 ]65 };66 pickles.push(pickle);67 });68 });69 }70 function createPickleArguments(argument, variableCells, valueCells) {71 var result = [];72 if (!argument) return result;73 if (argument.type === 'DataTable') {74 var table = {75 rows: argument.rows.map(function (row) {76 return {77 cells: row.cells.map(function (cell) {78 return {79 location: pickleLocation(cell.location),80 value: interpolate(cell.value, variableCells, valueCells)81 };82 })83 };84 })85 };86 result.push(table);87 } else if (argument.type === 'DocString') {88 var docString = {89 location: pickleLocation(argument.location),90 content: interpolate(argument.content, variableCells, valueCells),91 };92 if(argument.contentType) {93 docString.contentType = interpolate(argument.contentType, variableCells, valueCells);94 }95 result.push(docString);96 } else {97 throw Error('Internal error');98 }99 return result;100 }101 function interpolate(name, variableCells, valueCells) {102 variableCells.forEach(function (variableCell, n) {103 var valueCell = valueCells[n];104 var search = new RegExp('<' + variableCell.value + '>', 'g');105 // JS Specific - dollar sign needs to be escaped with another dollar sign106 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_string_as_a_parameter107 var replacement = valueCell.value.replace(new RegExp('\\$', 'g'), '$$$$')108 name = name.replace(search, replacement);109 });110 return name;111 }112 function pickleSteps(scenarioDefinition) {113 return scenarioDefinition.steps.map(function (step) {114 return pickleStep(step);115 });116 }117 function pickleStep(step) {118 return {119 text: step.text,120 arguments: createPickleArguments(step.argument, [], []),121 locations: [pickleStepLocation(step)]122 }123 }124 function pickleStepLocation(step) {125 return {126 line: step.location.line,127 column: step.location.column + (step.keyword ? countSymbols(step.keyword) : 0)128 };129 }130 function pickleLocation(location) {131 return {...

Full Screen

Full Screen

issue_helpers.js

Source:issue_helpers.js Github

copy

Full Screen

1import _ from 'lodash'2import { getStepMessages } from './step_result_helpers'3import indentString from 'indent-string'4import { Status, formatterHelpers } from 'cucumber'5import figures from 'figures'6import Table from 'cli-table3'7import { buildStepArgumentIterator } from '../../step_arguments'89const CHARACTERS = {10 [Status.AMBIGUOUS]: figures.cross,11 [Status.FAILED]: figures.cross,12 [Status.PASSED]: figures.tick,13 [Status.PENDING]: '?',14 [Status.SKIPPED]: '-',15 [Status.UNDEFINED]: '?',16}1718const IS_ISSUE = {19 [Status.AMBIGUOUS]: true,20 [Status.FAILED]: true,21 [Status.PASSED]: false,22 [Status.PENDING]: true,23 [Status.SKIPPED]: false,24 [Status.UNDEFINED]: true,25}2627function formatDataTable(arg) {28 const rows = arg.rows.map(row =>29 row.cells.map(cell =>30 cell.value.replace(/\\/g, '\\\\').replace(/\n/g, '\\n')31 )32 )33 const table = new Table({34 chars: {35 bottom: '',36 'bottom-left': '',37 'bottom-mid': '',38 'bottom-right': '',39 left: '|',40 'left-mid': '',41 mid: '',42 'mid-mid': '',43 middle: '|',44 right: '|',45 'right-mid': '',46 top: '',47 'top-left': '',48 'top-mid': '',49 'top-right': '',50 },51 style: {52 border: [],53 'padding-left': 1,54 'padding-right': 1,55 },56 })57 table.push(...rows)58 return table.toString()59}6061function formatDocString(arg) {62 return `"""\n${arg.content}\n"""`63}6465function formatStep({66 colorFns,67 isBeforeHook,68 keyword,69 keywordType,70 pickleStep,71 testStep,72}) {73 const status = testStep.issues ? testStep.issues[0].status : Status.PASSED74 const colorFn = colorFns[status]7576 let identifier77 if (testStep.sourceLocation && pickleStep) {78 identifier = keyword + (pickleStep.text || '')79 } else {80 identifier = isBeforeHook ? 'Before' : 'After'81 }8283 let text = colorFn(`${CHARACTERS[status]} ${identifier}`)8485 const { actionLocation } = testStep86 if (actionLocation) {87 text += ` # ${colorFns.location(88 formatterHelpers.formatLocation(actionLocation)89 )}`90 }91 text += '\n'9293 if (pickleStep) {94 let str95 const iterator = buildStepArgumentIterator({96 dataTable: arg => (str = formatDataTable(arg)),97 docString: arg => (str = formatDocString(arg)),98 })99 _.each(pickleStep.arguments, iterator)100 if (str) {101 text += indentString(`${colorFn(str)}\n`, 4)102 }103 }104105 if (testStep.attachments) {106 testStep.attachments.forEach(({ media, data }) => {107 const message = media.type === 'text/plain' ? `: ${data}` : ''108 text += indentString(`Attachment (${media.type})${message}\n`, 4)109 })110 }111112 const message = getStepMessages({113 colorFns,114 testStep,115 })116 if (message) {117 text += `${indentString(message, 4)}\n`118 }119 return text120}121122export function isIssue(status) {123 return IS_ISSUE[status]124}125126export function formatIssue({127 colorFns,128 gherkinDocument,129 number,130 pickle,131 testCase,132}) {133 const prefix = `${number}) `134 let text = prefix135 const scenarioLocation = formatterHelpers.formatLocation(136 testCase.sourceLocation137 )138 text += `Scenario: ${pickle.name} # ${colorFns.location(scenarioLocation)}\n`139 const stepLineToKeywordMap = formatterHelpers.GherkinDocumentParser.getStepLineToKeywordMap(140 gherkinDocument141 )142 const stepLineToPickledStepMap = formatterHelpers.PickleParser.getStepLineToPickledStepMap(143 pickle144 )145 let isBeforeHook = true146 let previousKeywordType = formatterHelpers.KeywordType.PRECONDITION147 _.each(testCase.steps, testStep => {148 isBeforeHook = isBeforeHook && !testStep.sourceLocation149 let keyword, keywordType, pickleStep150 // testStep.sourceLocation= {line:_.last(pickle.steps[testStep.index].locations).line,uri:testCase.sourceLocation.uri}151 if (testStep.sourceLocation) {152 pickleStep = stepLineToPickledStepMap[testStep.sourceLocation.line]153 if (pickleStep) {154 keyword = formatterHelpers.PickleParser.getStepKeyword({155 pickleStep,156 stepLineToKeywordMap,157 })158 keywordType = formatterHelpers.getStepKeywordType({159 keyword,160 language: gherkinDocument.feature.language,161 previousKeywordType,162 })163 }164 }165 const formattedStep = formatStep({166 colorFns,167 isBeforeHook,168 keyword,169 keywordType,170 pickleStep,171 testStep,172 })173 text += indentString(formattedStep, prefix.length)174 previousKeywordType = keywordType175 })176 // \n177 return `${text}` ...

Full Screen

Full Screen

PrettyFormatter.js

Source:PrettyFormatter.js Github

copy

Full Screen

1const {Status, SummaryFormatter } = require('cucumber');2const STATUS_CHARACTER_MAPPING = {3 [Status.AMBIGUOUS]: '~',4 [Status.FAILED]: '×',5 [Status.PASSED]: '√',6 [Status.PENDING]: '/',7 [Status.SKIPPED]: '-',8 [Status.UNDEFINED]: '?',9}10/**11 * Provide pretty formatting of test results12 */13class PrettyFormatter extends SummaryFormatter {14 constructor(options) {15 super(options)16 options.eventBroadcaster17 .on('test-case-started', this.logTestCaseName.bind(this))18 .on('test-step-finished', this.logTestStep.bind(this))19 .on('test-case-finished', this.logSeparator.bind(this))20 this.scenarioCount = 1;21 }22 logTestCaseName({sourceLocation}) {23 const {pickle} = this.eventDataCollector.getTestCaseData(sourceLocation)24 this.log(`${this.scenarioCount++}) Scenario: ${pickle.name} ${this.colorFns['location'](sourceLocation.uri + ':' + sourceLocation.line)}\n`);25 }26 logTestStep({testCase, index, result}) {27 const {gherkinKeyword, pickleStep, testStep} = this.eventDataCollector.getTestStepData({testCase, index});28 const {status} = result;29 // Log the step30 if (pickleStep) {31 this.log(` ${this.colorFns[status](STATUS_CHARACTER_MAPPING[status])} ${gherkinKeyword}${pickleStep.text}\n`); 32 }33 // Log attachments for the test step34 if(testStep && testStep.attachments){35 for(const attachment of testStep.attachments){36 const type = attachment.media.type;37 this.log(` ${this.colorFns['location'](`Attachment (${type})${type === 'text/plain' ? ': ' + attachment.data : ''}`)}\n`);38 }39 }40 }41 logSeparator() {42 this.log('\n');43 }44}...

Full Screen

Full Screen

inlineCucumberFormatter.js

Source:inlineCucumberFormatter.js Github

copy

Full Screen

1const { SummaryFormatter, formatterHelpers, Status } = require('cucumber');2class InlineFormatter extends SummaryFormatter {3 constructor(options) {4 super(options);5 options.eventBroadcaster.on('test-step-started', (stepData) => {6 this.logTestStepStarted(stepData);7 });8 options.eventBroadcaster.on('test-step-finished', () => this.log('\n'));9 }10 logTestStepStarted(stepData) {11 const testCaseAttempt = this.eventDataCollector.getTestCaseAttempt(stepData.testCase);12 const { gherkinDocument, pickle, testCase } = testCaseAttempt;13 const stepLineToKeywordMap = formatterHelpers.GherkinDocumentParser.getStepLineToKeywordMap(gherkinDocument);14 const stepLineToPickledStepMap = formatterHelpers.PickleParser.getStepLineToPickledStepMap(pickle);15 const testStep = testCase.steps[stepData.index];16 if (!testStep.sourceLocation) { return; }17 const stepText = this.buildStepText(stepLineToPickledStepMap, testStep, stepLineToKeywordMap);18 this.log(this.colorFns[Status.SKIPPED](stepText));19 }20 buildStepText(stepLineToPickledStepMap, testStep, stepLineToKeywordMap) {21 const pickleStep = stepLineToPickledStepMap[testStep.sourceLocation.line];22 const keyword = formatterHelpers.PickleParser.getStepKeyword({23 pickleStep: pickleStep,24 stepLineToKeywordMap: stepLineToKeywordMap25 });26 const separator = 'Given ' === keyword ? `${'-'.repeat(100)}\n\n` : '';27 const stepText = `${separator}${keyword}${pickleStep.text}\n`;28 return stepText;29 }30}...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var Cucumber = require('cucumber');2var fs = require('fs');3var gherkin = require('gherkin');4var parser = new gherkin.Parser();5var lexer = new gherkin.Lexer('en');6var gherkinDocument = parser.parse(lexer.lex('feature: test'));7var pickles = Cucumber.PickleCompiler.compile(gherkinDocument, 'test.feature');8var pickle = pickles[0];9var pickleStep = pickle.steps[0];10console.log(pickleStep.text);11console.log(pickleStep.argument);12import { Given, When, Then } from 'cucumber';13import { expect } from 'chai';14Given('the following products', function (table) {15 return 'pending';16});17When('I search for {string}', function (string) {18 return 'pending';19});20Then('I should see the following products', function (table) {21 return 'pending';22});23import { Given, When, Then } from 'cucumber';24import { expect } from 'chai';25Given('the following products', function (table) {26 return 'pending';27});28When('I search for {string}', function (string) {29 return 'pending';30});31Then('I should see the following products', function (table) {32 console.log(table.raw());33 console.log(table.hashes());34 return 'pending';35});36I want to get the table from the step definition. I have tried to use table.raw() but

Full Screen

Using AI Code Generation

copy

Full Screen

1var gherkin = require('cucumber-gherkin');2var fs = require('fs');3var gherkinSource = fs.readFileSync('test.feature', 'utf8');4var pickle = gherkin.pickles(gherkinSource)[0];5console.log(pickle);6{ name: 'Test scenario',7 [ { text: 'I have 1 cookie in my cookie jar',8 locations: [Array] } ],9 uri: 'test.feature' }10var gherkin = require('cucumber-gherkin');11var fs = require('fs');12var gherkinSource = fs.readFileSync('test.feature', 'utf8');13var pickle = gherkin.pickles(gherkinSource)[0];14console.log(pickle);15var step = pickle.steps[0];16console.log(step.text);17console.log(step.locations[0]);18{ line: 3, column: 5 }

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(new Cucumber.TokenScanner(gherkin));5var astTree = parser.parse();6var pickles = Cucumber.Compiler.compile(astTree, 'test.feature');7console.log(pickles[0].steps[0].pickleStep);

Full Screen

Using AI Code Generation

copy

Full Screen

1var gherkin = require('cucumber-gherkin');2var fs = require('fs');3var gherkinSource = fs.readFileSync('test.feature').toString();4var options = {5};6var gherkinDocument = gherkin.parse(gherkinSource, options);7var pickle = gherkinDocument.pickles[0];8var step = pickle.steps[0];9var source = gherkinDocument.feature.children[0].steps[0].location.source;10var stepName = step.text;11console.log(source);12console.log(stepName);

Full Screen

Using AI Code Generation

copy

Full Screen

1var Cucumber = require('cucumber');2var fs = require('fs');3var path = require('path');4var featureFile = path.join(__dirname, 'test.feature');5var featureSource = fs.readFileSync(featureFile, 'utf8');6var parser = new Cucumber.Parser();7var feature = parser.parse(featureSource);8var pickleStep = feature.getPickles()[0].steps[0];9console.log(pickleStep.source);10console.log(pickleStep.text);11Your name to display (optional):12Your name to display (optional):

Full Screen

Using AI Code Generation

copy

Full Screen

1var Cucumber = require('cucumber');2var gherkin = Cucumber.Gherkin;3var parser = new gherkin.Parser();4Given I am testing';5var feature = parser.parse(featureSource);6var pickle = new Cucumber.Pickle(feature.scenarioDefinitions[0], 'test.feature');7var step = pickle.steps[0];8var pickleStep = new Cucumber.PickleStep(step, 'test.feature', 1);9console.log(pickleStep);10PickleStep {11 line: 2 }

Full Screen

Using AI Code Generation

copy

Full Screen

1var Cucumber = require('cucumber');2var fs = require('fs');3var gherkin = fs.readFileSync('C:/Users/xxx/Downloads/xxx.feature', 'utf8');4var pickleStep = Cucumber.PickleStep;5var pickle = pickleStep(gherkin);6console.log(pickle);7var Cucumber = require('cucumber');8var fs = require('fs');9var gherkin = fs.readFileSync('C:/Users/xxx/Downloads/xxx.feature', 'utf8');10var pickleStep = Cucumber.PickleStep;11var pickle = pickleStep(gherkin);12console.log(pickle);13var Cucumber = require('cucumber');14var fs = require('fs');15var gherkin = fs.readFileSync('C:/Users/xxx/Downloads/xxx.feature', 'utf8');16var pickleStep = Cucumber.PickleStep;17var pickle = pickleStep(gherkin);18console.log(pickle);19var Cucumber = require('cucumber');20var fs = require('fs');21var gherkin = fs.readFileSync('C:/Users/xxx/Downloads/xxx.feature', 'utf8');

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