UNPKG

@amiceli/vitest-cucumber

Version:

vitest tools to use Gherkin feature in unit tests

59 lines (58 loc) 2.32 kB
import { onTestFailed, test } from 'vitest'; import { getVitestCucumberConfiguration } from '../configuration'; import { defineStepToTest, orderStepsToRun } from './define-step-test'; export function createBackgroundDescribeHandler({ background, predefinedSteps, backgroundCallback, }) { let backgroundStepsToRun = []; const config = getVitestCucumberConfiguration(); const createScenarioStepCallback = (stepType) => { return (stepDetails, scenarioStepCallback) => { backgroundStepsToRun.push(defineStepToTest({ parent: background, stepDetails, stepType, scenarioStepCallback, })); }; }; const scenarioStepsCallback = { Given: createScenarioStepCallback(`Given`), And: createScenarioStepCallback(`And`), context: {}, }; backgroundCallback(scenarioStepsCallback); const missingSteps = background.steps.filter((step) => { return (backgroundStepsToRun.find((s) => { return step.matchStep(s.step); }) === undefined); }); for (const predefineStep of predefinedSteps) { const missingStep = missingSteps.find((s) => { return s.matchStep(predefineStep.step); }); if (missingStep) { backgroundStepsToRun.push(defineStepToTest({ parent: background, stepDetails: predefineStep.step.details, stepType: predefineStep.step.type, scenarioStepCallback: predefineStep.fn, })); } } backgroundStepsToRun = orderStepsToRun(background, backgroundStepsToRun); background.checkIfStepWasCalled(); return function backgroundDescribe() { test.for(backgroundStepsToRun.map((s) => { return [s.key, s]; }))(`%s`, async ([, scenarioStep], ctx) => { onTestFailed(({ task }) => { const message = task.result?.errors?.at(0)?.message; config.onStepError({ error: new Error(message || `${scenarioStep.step.details} failed`), ctx, step: scenarioStep.step, }); }); await scenarioStep.fn(ctx, ...scenarioStep.params); }); }; }