diff --git a/addon-test-support/setup-middleware-reporter.ts b/addon-test-support/setup-middleware-reporter.ts index ccf6bff8..9692f11c 100644 --- a/addon-test-support/setup-middleware-reporter.ts +++ b/addon-test-support/setup-middleware-reporter.ts @@ -38,6 +38,30 @@ let currentViolationsMap: Map | undefined = undefined; let currentUrls: Set | undefined; let currentRouteNames: Set | undefined; +/** + * Utility to retrieve the route name corresponding to the current test. Absorbs the emitted + * assertion error if route name is `null`, resulting in an empty string return value. + * + * @param getFn Function to use to derive the route name. + * @returns Route name or empty string. + */ +export function _getCurrentRouteName(getFn = currentRouteName): string { + let routeName = ''; + + try { + routeName = getFn(); + } catch (error: unknown) { + if ( + error instanceof Error && + !/currentRouteName (\w|\s)+ string/.test(error.message) + ) { + throw error; + } + } + + return routeName; +} + /** * A custom reporter that is invoked once per failed a11yAudit call. This can be called * multiple times per test, and the results are accumulated until testDone. @@ -73,7 +97,7 @@ export async function middlewareReporter(axeResults: AxeResults) { } currentUrls!.add(currentURL()); - currentRouteNames!.add(currentRouteName()); + currentRouteNames!.add(_getCurrentRouteName()); axeResults.violations.forEach((violation) => { let rule = currentViolationsMap!.get(violation.id); diff --git a/tests/unit/get-current-route-name-test.ts b/tests/unit/get-current-route-name-test.ts new file mode 100644 index 00000000..dd06e1c7 --- /dev/null +++ b/tests/unit/get-current-route-name-test.ts @@ -0,0 +1,37 @@ +import { module, test } from 'qunit'; +import { setupTest } from 'ember-qunit'; +import { _getCurrentRouteName } from 'ember-a11y-testing/test-support/setup-middleware-reporter'; + +module('Unit | Utils | _getCurrentRouteName', function (hooks) { + setupTest(hooks); + + test('gets the route name for the current test', function (assert) { + function mockCurrentRouteName(): string { + return 'index'; + } + + const result = _getCurrentRouteName(mockCurrentRouteName); + + assert.strictEqual(result, 'index'); + }); + + test('absorbs `currentRouteName` error when route name is null', function (assert) { + function currentRouteNameMock(): string { + throw new Error('currentRouteName shoudl be a string'); + } + + const result = _getCurrentRouteName(currentRouteNameMock); + + assert.strictEqual(result, ''); + }); + + test('bubbles up all other emitted errors', function (assert) { + function mockCurrentRouteName(): string { + throw new Error('Catastrophic error!'); + } + + assert.throws(() => { + _getCurrentRouteName(mockCurrentRouteName); + }, /Catastrophic error!/); + }); +});