From 8abb01f028a08a5d3d201ec78a4b81d454bc5d0d Mon Sep 17 00:00:00 2001 From: Landon Martin Date: Wed, 25 Nov 2026 17:00:39 -0500 Subject: [PATCH 1/2] fix: print an assertion's customMessage once when its template includes it --- lib/assert/error.js | 3 ++- test/unit/assert/error_test.js | 15 +++++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) create mode 100644 test/unit/assert/error_test.js diff --git a/lib/assert/error.js b/lib/assert/error.js index 1b11b10a4..1e81239b8 100644 --- a/lib/assert/error.js +++ b/lib/assert/error.js @@ -20,7 +20,8 @@ function AssertionFailedError(params, template) { this.inspect = () => { const params = this.params || {} const msg = params.customMessage || '' - return msg + subs(this.template, params) + const text = subs(this.template, params) + return this.template.includes('{{customMessage}}') ? text : msg + text } this.cliMessage = () => this.inspect() diff --git a/test/unit/assert/error_test.js b/test/unit/assert/error_test.js new file mode 100644 index 000000000..75c713ef7 --- /dev/null +++ b/test/unit/assert/error_test.js @@ -0,0 +1,15 @@ +import { expect } from 'chai' + +import AssertionFailedError from '../../../lib/assert/error.js' + +describe('AssertionFailedError', () => { + it('should print a custom message once when the template includes it', () => { + const err = new AssertionFailedError({ subject: 'web page', customMessage: 'Order never reached paid\n\n' }, '{{customMessage}}expected {{subject}} to include "Paid"') + expect(err.inspect()).to.equal('Order never reached paid\n\nexpected web page to include "Paid"') + }) + + it('should put a custom message first when the template does not include it', () => { + const err = new AssertionFailedError({ customMessage: 'Scrolled to the end and element was not found' }, '') + expect(err.inspect()).to.equal('Scrolled to the end and element was not found') + }) +}) From cf728f8c6ef52d8fe8b157fd8a24f9336afb70bb Mon Sep 17 00:00:00 2001 From: Landon Martin Date: Wed, 25 Nov 2026 17:00:39 -0500 Subject: [PATCH 2/2] feat: add step.customMessage() to print a message above a failed step's error Pass step.customMessage('...') as a step's last argument, or chain .customMessage('...') on the step. When the step fails, the message is printed above the original error, which is indented under it. Steps that never ran because an earlier step failed keep the original error. --- docs/assertions.md | 18 +++++ lib/actor.js | 1 + lib/step/config.js | 13 +++- lib/step/record.js | 17 ++++- lib/steps.js | 6 ++ .../step-enhancements/custom_helper.js | 4 ++ .../step-enhancements_test.js | 9 +++ test/runner/step-enhancements_test.js | 19 +++++ test/unit/actor_test.js | 72 +++++++++++++++++++ typings/index.d.ts | 3 + 10 files changed, 160 insertions(+), 2 deletions(-) diff --git a/docs/assertions.md b/docs/assertions.md index aa9c097be..75000d4ae 100644 --- a/docs/assertions.md +++ b/docs/assertions.md @@ -64,6 +64,24 @@ I.seeInTitle('Admin — Orders') I.seeCookie('session') ``` +### Custom Failure Messages + +A failing step reports the helper's own error, which says what was missing but not why the test needed it. Pass `step.customMessage()` as the step's last argument, or chain `.customMessage()` on the step, and the message is printed above the original error: + +```js +import step from 'codeceptjs/steps' + +I.waitForVisible('#checkout', 10, step.customMessage('Checkout never loaded after login')) +I.see('Paid', '.order-status').customMessage('Order never reached the paid state') +``` + +``` +Checkout never loaded after login + element (#checkout) still not visible after 10 sec +``` + +It works for any step, not only assertions, and combines with other step options: `step.timeout(5).customMessage('...')`. + ## Custom Assertions ### When You Need Custom Assertions diff --git a/lib/actor.js b/lib/actor.js index 73022d78f..cd045d36b 100644 --- a/lib/actor.js +++ b/lib/actor.js @@ -44,6 +44,7 @@ function addStepConfigChain(promise, step) { promise.at = position => promise.stepConfig(new StepConfig({ elementIndex: position })) promise.timeout = seconds => promise.stepConfig(new StepConfig().timeout(seconds)) promise.retry = retry => promise.stepConfig(new StepConfig().retry(retry)) + promise.customMessage = message => promise.stepConfig(new StepConfig().customMessage(message)) return promise } diff --git a/lib/step/config.js b/lib/step/config.js index 6e7ba1f34..b8f2ecf1b 100644 --- a/lib/step/config.js +++ b/lib/step/config.js @@ -13,11 +13,12 @@ */ class StepConfig { constructor(opts = {}) { - /** @member {{ opts: StepOptions, timeout: number|undefined, retry: number|undefined }} */ + /** @member {{ opts: StepOptions, timeout: number|undefined, retry: number|undefined, customMessage: string|undefined }} */ this.config = { opts, timeout: undefined, retry: undefined, + customMessage: undefined, } this.__isStepConfig = true } @@ -56,6 +57,16 @@ class StepConfig { return this } + /** + * Set a message to print above the step's error if the step fails. + * @param {string} message - The message for the step's failure. + * @returns {StepConfig} - The step configuration object. + */ + customMessage(message) { + this.config.customMessage = message + return this + } + getConfig() { return this.config } diff --git a/lib/step/record.js b/lib/step/record.js index 29e7d71d6..3b0e3dfdb 100644 --- a/lib/step/record.js +++ b/lib/step/record.js @@ -6,9 +6,10 @@ import store from '../store.js' import { TIMEOUT_ORDER } from '../timeout.js' import retryStep, { releaseStepRetry } from './retry.js' import { fixErrorStack } from '../utils/typescript.js' +import AssertionFailedError from '../assert/error.js' function applyStepConfig(step, stepConfig) { - const { opts, timeout, retry } = stepConfig.getConfig() + const { opts, timeout, retry, customMessage } = stepConfig.getConfig() if (opts) { output.debug(`Step ${step.title}: options applied ${JSON.stringify(opts)}`) @@ -20,6 +21,18 @@ function applyStepConfig(step, stepConfig) { step.setTimeout(timeout * 1000, TIMEOUT_ORDER.codeLimitTime) } if (retry) retryStep(step, retry) + if (customMessage) step.customMessage = customMessage +} + +function addCustomMessage(err, message) { + if (err instanceof AssertionFailedError) { + err.params.customMessage = `${message}\n ${err.params.customMessage || ''}` + return + } + const original = err.message + const stack = err.stack + err.message = original ? `${message}\n${original.replace(/^/gm, ' ')}` : message + if (original && typeof stack === 'string') err.stack = stack.replace(original, () => err.message) } function recordStep(step, args) { @@ -71,6 +84,8 @@ function recordStep(step, args) { if (fileMapping) { fixErrorStack(err, fileMapping) } + + if (step.customMessage && step.startTime) addCustomMessage(err, step.customMessage) event.emit(event.step.failed, step, err) event.emit(event.step.finished, step) diff --git a/lib/steps.js b/lib/steps.js index c1d2af911..375f13de4 100644 --- a/lib/steps.js +++ b/lib/steps.js @@ -12,6 +12,10 @@ function stepRetry(retry) { return new StepConfig().retry(retry) } +function stepCustomMessage(message) { + return new StepConfig().customMessage(message) +} + function section(name) { if (!name) return endSection() return new SectionClass(name).start() @@ -28,11 +32,13 @@ const step = { opts: stepOpts, timeout: stepTimeout, retry: stepRetry, + customMessage: stepCustomMessage, // one-function syntax stepTimeout, stepRetry, stepOpts, + stepCustomMessage, // sections section, diff --git a/test/data/sandbox/configs/step-enhancements/custom_helper.js b/test/data/sandbox/configs/step-enhancements/custom_helper.js index f75ef1e6c..102e956d9 100644 --- a/test/data/sandbox/configs/step-enhancements/custom_helper.js +++ b/test/data/sandbox/configs/step-enhancements/custom_helper.js @@ -10,6 +10,10 @@ class MyHelper { } } + failWithDetails() { + throw new Error('element (#checkout) still not visible\nwaited 1 sec') + } + wait(timeout) { return new Promise(resolve => setTimeout(resolve, timeout)) } diff --git a/test/data/sandbox/configs/step-enhancements/step-enhancements_test.js b/test/data/sandbox/configs/step-enhancements/step-enhancements_test.js index 629fe0d63..d0d862014 100644 --- a/test/data/sandbox/configs/step-enhancements/step-enhancements_test.js +++ b/test/data/sandbox/configs/step-enhancements/step-enhancements_test.js @@ -12,3 +12,12 @@ Scenario('test step timeouts', ({ I }) => { Scenario('test step retry', ({ I }) => { I.retryFewTimesAndPass(3, step.retry(4)) }) + +Scenario('test step custom message', ({ I }) => { + I.failWithDetails(step.customMessage('Checkout never loaded')) +}) + +Scenario('test assertion custom message', ({ I }) => { + I.seeFile('codecept.conf.js') + I.seeInThisFile('Paid', step.customMessage('Order never reached paid')) +}) diff --git a/test/runner/step-enhancements_test.js b/test/runner/step-enhancements_test.js index c32d41707..44babc027 100644 --- a/test/runner/step-enhancements_test.js +++ b/test/runner/step-enhancements_test.js @@ -38,6 +38,25 @@ describe('CodeceptJS step-enhancements', function () { }) }) + it('should print a step custom message above the error', done => { + exec(config_run_config('codecept.conf.js', 'step custom message'), (err, stdout) => { + debug(stdout) + expect(err).toBeTruthy() + expect(stdout).toContain('Checkout never loaded\n element (#checkout) still not visible\n waited 1 sec') + done() + }) + }) + + it('should print a step custom message above an assertion error', done => { + exec(config_run_config('codecept.conf.js', 'assertion custom message'), (err, stdout) => { + debug(stdout) + expect(err).toBeTruthy() + expect(stdout).toContain('Order never reached paid\n expected file') + expect(stdout.match(/Order never reached paid/g)).toHaveLength(1) + done() + }) + }) + it('should apply step retry', done => { exec(config_run_config('codecept.conf.js', 'retry', true), (err, stdout) => { debug(stdout) diff --git a/test/unit/actor_test.js b/test/unit/actor_test.js index d380be2b4..f82638ac9 100644 --- a/test/unit/actor_test.js +++ b/test/unit/actor_test.js @@ -8,6 +8,7 @@ import recorder from '../../lib/recorder.js' import step from '../../lib/steps.js' import event from '../../lib/event.js' import store from '../../lib/store.js' +import AssertionFailedError from '../../lib/assert/error.js' const __filename = fileURLToPath(import.meta.url) const __dirname = path.dirname(__filename) @@ -29,6 +30,12 @@ describe('Actor', () => { }, _hidden: () => 'hidden', slow: () => new Promise(resolve => setTimeout(resolve, 200)), + dieWithDetails: () => { + throw new Error('ups\nwaited 5 sec') + }, + failAssertion: () => { + throw new AssertionFailedError({ subject: 'web page', customMessage: '' }, '{{customMessage}}expected {{subject}} to include "Paid"') + }, failAfter: (i = 1) => { counter++ if (counter <= i) throw new Error('ups') @@ -328,4 +335,69 @@ describe('Actor', () => { expect(() => promise.retry(1)).toThrow('already') }) }) + + describe('step custom message', () => { + beforeEach(() => { + recorder.retries = [] + recorder.start() + }) + + afterEach(() => { + recorder.stop() + recorder.reset() + recorder.retries = [] + }) + + const failure = promise => promise.then( + () => { + throw new Error('step passed') + }, + err => err, + ) + + it('should put a custom message above the error of a failed step', async () => { + const err = await failure(I.die(step.customMessage('Login never finished'))) + expect(err.message).toEqual('Login never finished\n ups') + }) + + it('should accept a chained custom message', async () => { + const err = await failure(I.die().customMessage('Login never finished')) + expect(err.message).toEqual('Login never finished\n ups') + }) + + it('should combine a custom message with other step options in any order', async () => { + let startedOpts + event.dispatcher.on(event.step.started, started => (startedOpts = started.opts)) + const err = await failure(I.die(step.customMessage('Login never finished').opts({ exact: true }).timeout(5))) + expect(err.message).toEqual('Login never finished\n ups') + expect(startedOpts).toEqual({ exact: true }) + }) + + it('should indent every line of a multi-line error', async () => { + const err = await failure(I.dieWithDetails(step.customMessage('Login never finished'))) + expect(err.message).toEqual('Login never finished\n ups\n waited 5 sec') + }) + + it('should show the custom message once at the top of the stack', async () => { + const err = await failure(I.die(step.customMessage('Login never finished'))) + expect(err.stack.split('\n')[0]).toEqual('Error: Login never finished') + expect(err.stack.match(/Login never finished/g)).toHaveLength(1) + }) + + it('should put a custom message above a failed assertion', async () => { + const err = await failure(I.failAssertion(step.customMessage('Order never reached paid'))) + expect(err.inspect()).toEqual('Order never reached paid\n expected web page to include "Paid"') + }) + + it('should not add a custom message to a step that never ran', async () => { + I.die() + const err = await failure(I.hello(step.customMessage('Hello never ran'))) + expect(err.message).toEqual('ups') + }) + + it('should leave the error of a step without a custom message unchanged', async () => { + const err = await failure(I.die()) + expect(err.message).toEqual('ups') + }) + }) }) diff --git a/typings/index.d.ts b/typings/index.d.ts index a8bbbcc0a..fa4e38388 100644 --- a/typings/index.d.ts +++ b/typings/index.d.ts @@ -531,6 +531,7 @@ declare namespace CodeceptJS { stepConfig(config: CodeceptJS.StepConfig): this timeout(seconds: number): this retry(retry: number | object): this + customMessage(message: string): this } interface ElementStepPromise extends StepPromise { @@ -806,9 +807,11 @@ declare module 'codeceptjs/steps' { opts(opts: CodeceptJS.StepOptions): CodeceptJS.StepConfig; timeout(timeout: number): CodeceptJS.StepConfig; retry(retry: number): CodeceptJS.StepConfig; + customMessage(message: string): CodeceptJS.StepConfig; stepOpts(opts: CodeceptJS.StepOptions): CodeceptJS.StepConfig; stepTimeout(timeout: number): CodeceptJS.StepConfig; stepRetry(retry: number): CodeceptJS.StepConfig; + stepCustomMessage(message: string): CodeceptJS.StepConfig; section(name: string): any; endSection(): any; Section(name: string): any;