UNPKG

@amiceli/vitest-cucumber

Version:

vitest tools to use Gherkin feature in unit tests

74 lines (73 loc) 2.81 kB
import { SyntaxKind } from 'ts-morph'; import { generateStep } from '../../../scripts/generateFile'; import { ExpressionStep } from '../../parser/expression/ExpressionStep'; import { AstUtils } from './AstUtils'; import { BaseAst } from './BaseAst'; export class StepAst extends BaseAst { stepableParent; stepParentFunction; constructor(options) { super(options); this.stepableParent = options.stepParent; this.stepParentFunction = options.stepParentFunction; } static fromOptions(options) { return new StepAst(options); } handleSteps() { const stepExpressions = this.getStepExpressions(); const stepsToAdd = this.getStepsToAdd(stepExpressions); const stepsToRemove = this.getStepsToRemove(stepExpressions); for (const s of stepsToRemove) { if (this.shouldComment) { this.commentExpression(this.stepParentFunction, s.callExpression); } else { this.removeChildFromParent(this.stepParentFunction, s.callExpression); } } for (const step of stepsToAdd) { this.stepParentFunction.addStatements(generateStep(step)); } } getStepsToRemove(parentSteps) { return parentSteps.filter((stepExpression) => { const stepExistsInScenario = this.stepableParent.steps.some((step) => { return this.stepMatchCallExpression(stepExpression, step); }); return stepExistsInScenario === false; }); } getStepsToAdd(parentSteps) { return this.stepableParent.steps.filter((step) => { const stepIsInScenarioSpec = parentSteps.some((stepExpression) => { return this.stepMatchCallExpression(stepExpression, step); }); return !stepIsInScenarioSpec; }); } stepMatchCallExpression(stepExpression, step) { const match = ExpressionStep.matchStep(step, stepExpression.name); return match.length > 0 || stepExpression.name === step.details; } isStepLine(line) { const regex = /\b(Given|Then|When|And|But)\b/; return regex.test(line); } getStepExpressions() { return this.stepParentFunction .getDescendantsOfKind(SyntaxKind.CallExpression) .filter((call) => this.isStepLine(call.getText())) .map((callExpression) => { return { name: callExpression .getArguments() .find((arg) => AstUtils.isString(arg.getKind())) ?.getText() .replace(/^['"`]|['"`]$/g, ''), callExpression, }; }) .filter((step) => step?.name !== undefined); } }