Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
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
Next Next commit
feat: refactor within to Within with begin/end pattern
Add Within() function with three signatures:
- Within(locator) to begin scoped context
- Within() to end current context
- Within(locator, fn) callback pattern (existing behavior)

Lowercase within() kept as deprecated alias with one-time warning.
switchTo() in helpers auto-ends any active Within context.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
  • Loading branch information
DavertMik and claude committed Mar 26, 2026
commit b116fb7fcf5186c0c2d61ef29efbdd7237c1a9ac
73 changes: 18 additions & 55 deletions docs/effects.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,7 @@ Effects are functions that can modify scenario flow. They provide ways to handle
Effects can be imported directly from CodeceptJS:

```js
// ESM
import { tryTo, retryTo, within } from 'codeceptjs/effects'

// CommonJS
const { tryTo, retryTo, within } = require('codeceptjs/effects')
import { tryTo, retryTo, Within } from 'codeceptjs/effects'
```

> 📝 Note: Prior to v3.7, `tryTo` and `retryTo` were available globally via plugins. This behavior is deprecated and will be removed in v4.0.
Expand Down Expand Up @@ -80,71 +76,38 @@ await retryTo(tries => {
}, 3)
```

## within
## Within

The `within` effect scopes all actions inside it to a specific element on the page — useful when working with repeated UI components or narrowing interaction to a specific section.
The `Within` effect scopes actions to a specific element or iframe. It supports both a begin/end pattern and a callback pattern:

```js
import { within } from 'codeceptjs/effects'

// inside a test...
await within('.js-signup-form', () => {
I.fillField('user[login]', 'User')
I.fillField('user[email]', 'user@user.com')
I.fillField('user[password]', 'user@user.com')
I.click('button')
import { Within } from 'codeceptjs/effects'

// Begin/end pattern
Within('.modal')
I.see('Modal title')
I.click('Close')
Within()

// Callback pattern
Within('.modal', () => {
I.see('Modal title')
I.click('Close')
})
I.see('There were problems creating your account.')
```

> ⚠ `within` can cause problems when used incorrectly. If you see unexpected behavior, refactor to use the context parameter on individual actions instead (e.g. `I.click('Login', '.nav')`). Keep `within` for the simplest cases.

> ⚠ Since `within` returns a Promise, always `await` it when you need its return value.

### IFrames

Use a `frame` locator to scope actions inside an iframe:
See the full [Within documentation](/within) for details on iframes, page objects, and `await` usage.

```js
await within({ frame: '#editor' }, () => {
I.see('Page')
I.fillField('Body', 'Hello world')
})
```

Nested iframes _(WebDriver & Puppeteer only)_:

```js
await within({ frame: ['.content', '#editor'] }, () => {
I.see('Page')
})
```

> ℹ IFrames can also be accessed via `I.switchTo` command.

### Returning Values

`within` can return a value for use in the scenario:

```js
const val = await within('#sidebar', () => {
return I.grabTextFrom({ css: 'h1' })
})
I.fillField('Description', val)
```

When running steps inside a `within` block, they will be shown indented in the output.
> The lowercase `within()` is deprecated. Use `Within` instead.

## Usage with TypeScript

Effects are fully typed and work well with TypeScript:

```ts
import { tryTo, retryTo, within } from 'codeceptjs/effects'
import { tryTo, retryTo, Within } from 'codeceptjs/effects'

const success = await tryTo(async () => {
await I.see('Element')
})
```

This documentation covers the main effects functionality while providing practical examples and important notes about deprecation and future changes. Let me know if you'd like me to expand any section or add more examples!
220 changes: 196 additions & 24 deletions docs/within.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,51 +5,223 @@ title: Within

# Within

`within` scopes all actions inside it to a specific element on the page — useful when working with repeated UI components or narrowing interaction to a specific section.
`Within` narrows the execution context to a specific element or iframe on the page. All actions called inside a `Within` block are scoped to the matched element.

```js
within('.js-signup-form', () => {
I.fillField('user[login]', 'User')
I.fillField('user[email]', 'user@user.com')
I.fillField('user[password]', 'user@user.com')
I.click('button')
import { Within } from 'codeceptjs/effects'
```

## Begin / End Pattern

The simplest way to use `Within` is the begin/end pattern. Call `Within` with a locator to start, perform actions, then call `Within()` with no arguments to end:

```js
Within('.signup-form')
I.fillField('Email', 'user@example.com')
I.fillField('Password', 'secret')
I.click('Sign Up')
Within()
```

Steps between `Within('.signup-form')` and `Within()` are scoped to `.signup-form`. After `Within()`, the context resets to the full page.

### Auto-end previous context

Starting a new `Within` automatically ends the previous one:

```js
Within('.sidebar')
I.click('Dashboard')

Within('.main-content') // ends .sidebar, begins .main-content
I.see('Welcome')
Within()
```

### Forgetting to close

If you forget to call `Within()` at the end, the context is automatically cleaned up when the test finishes. However, it is good practice to always close it explicitly.

## Callback Pattern

The callback pattern wraps actions in a function. The context is automatically closed when the function returns:

```js
Within('.signup-form', () => {
I.fillField('Email', 'user@example.com')
I.fillField('Password', 'secret')
I.click('Sign Up')
})
I.see('Account created')
```

### Returning values

The callback pattern supports returning values. Use `await` on both the `Within` call and the inner action:

```js
const text = await Within('#sidebar', async () => {
return await I.grabTextFrom('h1')
})
I.fillField('Search', text)
```

## When to use `await`

**Begin/end pattern** does not need `await`:

```js
Within('.form')
I.fillField('Name', 'John')
Within()
```

**Callback pattern** needs `await` when:

- The callback is `async`
- You need a return value from `Within`

```js
// async callback — await required
await Within('.form', async () => {
await I.click('Submit')
await I.waitForText('Done')
})
I.see('There were problems creating your account.')
```

> ⚠ `within` can cause problems when used incorrectly. If you see unexpected behavior, refactor to use the context parameter on individual actions instead (e.g. `I.click('Login', '.nav')`). Keep `within` for the simplest cases.
> Since `within` returns a Promise, always `await` it when you need its return value.
```js
// sync callback — no await needed
Within('.form', () => {
I.fillField('Name', 'John')
I.click('Submit')
})
```

## Working with IFrames

Use the `frame` locator to scope actions inside an iframe:

```js
// Begin/end
Within({ frame: 'iframe' })
I.fillField('Email', 'user@example.com')
I.click('Submit')
Within()

// Callback
Within({ frame: '#editor-frame' }, () => {
I.see('Page content')
})
```

## IFrames
### Nested IFrames

Use a `frame` locator to scope actions inside an iframe:
Pass an array of selectors to reach nested iframes:

```js
within({ frame: '#editor' }, () => {
I.see('Page')
I.fillField('Body', 'Hello world')
Within({ frame: ['.wrapper', '#content-frame'] }, () => {
I.fillField('Name', 'John')
I.see('Sign in!')
})
```

Nested iframes _(WebDriver & Puppeteer only)_:
Each selector in the array navigates one level deeper into the iframe hierarchy.

### switchTo auto-disables Within

If you call `I.switchTo()` while inside a `Within` context, the within context is automatically ended. This prevents conflicts between the two scoping mechanisms:

```js
Within('.sidebar')
I.click('Open editor')
I.switchTo('#editor-frame') // automatically ends Within('.sidebar')
I.fillField('content', 'Hello')
I.switchTo() // exits iframe
```

## Usage in Page Objects

In page objects, import `Within` directly:

```js
// pages/Login.js
import { Within } from 'codeceptjs/effects'

export default {
loginForm: '.login-form',

fillCredentials(email, password) {
Within(this.loginForm)
I.fillField('Email', email)
I.fillField('Password', password)
Within()
},

submitLogin(email, password) {
this.fillCredentials(email, password)
I.click('Log In')
},
}
```

```js
within({ frame: ['.content', '#editor'] }, () => {
I.see('Page')
// tests/login_test.js
Scenario('user can log in', ({ I, loginPage }) => {
I.amOnPage('/login')
loginPage.submitLogin('user@example.com', 'password')
I.see('Dashboard')
})
```

> ℹ IFrames can also be accessed via `I.switchTo` command.
The callback pattern also works in page objects:

```js
// pages/Checkout.js
import { Within } from 'codeceptjs/effects'

export default {
async getTotal() {
return await Within('.order-summary', async () => {
return await I.grabTextFrom('.total')
})
},
}
```

## Returning Values
## Deprecated: lowercase `within`

`within` can return a value for use in the scenario:
The lowercase `within()` is still available as a global function for backward compatibility, but it is deprecated:

```js
const val = await within('#sidebar', () => {
return I.grabTextFrom({ css: 'h1' })
// deprecated — still works, shows a one-time warning
within('.form', () => {
I.fillField('Name', 'John')
})

// recommended
import { Within } from 'codeceptjs/effects'
Within('.form', () => {
I.fillField('Name', 'John')
})
I.fillField('Description', val)
```

When running steps inside a `within` block, they will be shown indented in the output.
The global `within` only supports the callback pattern. For the begin/end pattern, you must import `Within`.

## Output

When running steps inside a `Within` block, the output shows them indented under the context:

```
Within ".signup-form"
I fill field "Email", "user@example.com"
I fill field "Password", "secret"
I click "Sign Up"
I see "Account created"
```

## Tips

- Prefer the begin/end pattern for simple linear flows — it's more readable.
- Use the callback pattern when you need return values or want guaranteed cleanup.
- Avoid deeply nesting `Within` blocks. If you find yourself needing nested contexts, consider restructuring your test.
- `Within` cannot be used inside a `session`. Use `session` at the top level and `Within` inside it, not the other way around.
Loading