@amiceli/vitest-cucumber
Version:
vitest tools to use Gherkin feature in unit tests
83 lines (82 loc) • 3.27 kB
JavaScript
import { SyntaxKind } from 'ts-morph';
import { generateRules } from '../../../scripts/generateFile';
import { BackgroundAst } from './BackgroundAst';
import { BaseAst } from './BaseAst';
import { ScenarioAst } from './ScenarioAst';
export class RuleAst extends BaseAst {
ruleParent;
ruleParentFunction;
constructor(options) {
super(options);
this.ruleParent = options.ruleParent;
this.ruleParentFunction = options.ruleParentFunction;
}
static fromOptions(options) {
return new RuleAst(options);
}
handleRules() {
const rulesArrow = this.getRulesArrowFunction();
const rulesToAdd = this.getMissingRules(rulesArrow);
const rulesToRemove = this.getRulesToRemove(rulesArrow);
for (const rule of rulesToRemove) {
if (this.shouldComment) {
this.commentExpression(this.ruleParentFunction, rule.callExpression);
}
else {
this.removeChildFromParent(this.ruleParentFunction, rule.callExpression);
}
}
this.ruleParentFunction.addStatements(generateRules(rulesToAdd || []));
for (const rule of this.ruleParent.rules) {
const ruleArrowFunction = this.getRuleArrowFunction(rule);
if (ruleArrowFunction) {
ScenarioAst.fromOptions({
...this.options,
stepableParent: rule,
stepableParentFunction: ruleArrowFunction,
forRule: true,
}).handleScenarii();
BackgroundAst.fromOptions({
...this.options,
stepableParent: rule,
stepableParentFunction: ruleArrowFunction,
forRule: true,
}).handleBackground();
this.updateRuleArgument(rule, ruleArrowFunction);
}
}
}
updateRuleArgument(rule, ruleArrowFunction) {
const ruleRequiredArgs = [
rule.background ? 'RuleBackground' : undefined,
rule.hasScenarioOutline ? 'RuleScenarioOutline' : undefined,
rule.hasScenario ? 'RuleScenario' : undefined,
].filter((s) => s !== undefined);
this.updateSyntaxListChild(ruleArrowFunction, ruleRequiredArgs);
}
getRuleArrowFunction(rule) {
const list = this.getRulesArrowFunction();
const scenarioFunction = list.find((s) => s.name === rule.name);
if (scenarioFunction) {
return scenarioFunction.callExpression
.getArguments()
.find((arg) => arg.isKind(SyntaxKind.ArrowFunction));
}
}
getRulesToRemove(parentScenarii) {
return parentScenarii.filter((rule) => {
return (rule.name &&
this.ruleParent.rules.map((s) => s.name).includes(rule.name) ===
false);
});
}
getMissingRules(parentScenarii) {
return this.ruleParent.rules.filter((scenario) => {
return (parentScenarii.map((s) => s.name).includes(scenario.name) ===
false);
});
}
getRulesArrowFunction() {
return this.callExpressionMatchRegExp(this.ruleParentFunction, /\bRule\(/);
}
}