Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions docs/assertions.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions lib/actor.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

Expand Down
3 changes: 2 additions & 1 deletion lib/assert/error.js
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
13 changes: 12 additions & 1 deletion lib/step/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down Expand Up @@ -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
}
Expand Down
17 changes: 16 additions & 1 deletion lib/step/record.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)}`)
Expand All @@ -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) {
Expand Down Expand Up @@ -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)
Expand Down
6 changes: 6 additions & 0 deletions lib/steps.js
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand All @@ -28,11 +32,13 @@ const step = {
opts: stepOpts,
timeout: stepTimeout,
retry: stepRetry,
customMessage: stepCustomMessage,

// one-function syntax
stepTimeout,
stepRetry,
stepOpts,
stepCustomMessage,

// sections
section,
Expand Down
4 changes: 4 additions & 0 deletions test/data/sandbox/configs/step-enhancements/custom_helper.js
Original file line number Diff line number Diff line change
Expand Up @@ -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))
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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'))
})
19 changes: 19 additions & 0 deletions test/runner/step-enhancements_test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
72 changes: 72 additions & 0 deletions test/unit/actor_test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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')
Expand Down Expand Up @@ -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')
})
})
})
15 changes: 15 additions & 0 deletions test/unit/assert/error_test.js
Original file line number Diff line number Diff line change
@@ -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')
})
})
3 changes: 3 additions & 0 deletions typings/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<T = any> extends StepPromise<T> {
Expand Down Expand Up @@ -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;
Expand Down
Loading