diff --git a/CHANGELOG.md b/CHANGELOG.md index bb84ac8..1e169c7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [Unreleased] +### Fixed +- Use RegExp.source to represent regular expression in messages ([#12](https://github.com/cucumber/javascript-core/pull/12)) ## [0.4.0] - 2025-08-26 ### Added diff --git a/src/SupportCodeBuilderImpl.ts b/src/SupportCodeBuilderImpl.ts index 348a2ef..22d06db 100644 --- a/src/SupportCodeBuilderImpl.ts +++ b/src/SupportCodeBuilderImpl.ts @@ -115,6 +115,7 @@ export class SupportCodeBuilderImpl implements SupportCodeBuilder { if (!compiled) { return undefined } + const source = this.extractPatternSource(pattern) return { id, expression: { @@ -131,7 +132,7 @@ export class SupportCodeBuilderImpl implements SupportCodeBuilder { this.expression.compiled instanceof CucumberExpression ? StepDefinitionPatternType.CUCUMBER_EXPRESSION : StepDefinitionPatternType.REGULAR_EXPRESSION, - source: pattern.toString(), + source, }, sourceReference, } @@ -141,6 +142,13 @@ export class SupportCodeBuilderImpl implements SupportCodeBuilder { .filter((step) => !!step) } + private extractPatternSource(pattern: string | RegExp) { + if (pattern instanceof RegExp) { + return pattern.flags ? pattern.toString() : pattern.source + } + return pattern + } + private compileExpression( text: string | RegExp ): CucumberExpression | RegularExpression | undefined { diff --git a/src/buildSupportCode.spec.ts b/src/buildSupportCode.spec.ts index be03ab7..a1fbf79 100644 --- a/src/buildSupportCode.spec.ts +++ b/src/buildSupportCode.spec.ts @@ -226,7 +226,41 @@ describe('buildSupportCode', () => { stepDefinition: { id: '0', pattern: { - source: '/there are (\\d+) widgets/', + source: 'there are (\\d+) widgets', + type: StepDefinitionPatternType.REGULAR_EXPRESSION, + }, + sourceReference: { + location: { + column: 1, + line: 1, + }, + uri: 'steps.js', + }, + }, + }, + ]) + }) + + it('handles regular expressions with flags', () => { + const library = buildSupportCode({ newId }) + .step({ + pattern: /there are (\d+) widgets/i, + fn: sinon.stub(), + sourceReference: { uri: 'steps.js', location: { line: 1, column: 1 } }, + }) + .build() + const matchedSteps = library.findAllStepsBy('there ARE 17 widgets') + + expect(matchedSteps.length).to.eq(1) + expect(matchedSteps[0].def.expression.compiled).to.be.instanceof(RegularExpression) + expect(matchedSteps[0].args.length).to.eq(1) + expect(matchedSteps[0].args[0].getValue(undefined)).to.eq(17) + expect(library.toEnvelopes()).to.deep.eq([ + { + stepDefinition: { + id: '0', + pattern: { + source: '/there are (\\d+) widgets/i', type: StepDefinitionPatternType.REGULAR_EXPRESSION, }, sourceReference: {