Spec-Zone.ru › Cypress

within

Ограничивает последующие команды cy внутри этого элемента. Полезно при работе внутри определенной группы элементов, например, в <form>.

Синтаксис

.within(callbackFn)
.within(options, callbackFn)

Использование

Правильное использование

cy.get('.list').within(($list) => {}) // Yield the `.list` and scope all commands within it

Неправильное использование

cy.within(() => {}) // Errors, cannot be chained off 'cy'
cy.getCookies().within(() => {}) // Errors, 'getCookies' does not yield DOM element

Аргументы

callbackFn (Функция)

Передайте функцию, которая принимает текущий возвращаемый объект в качестве первого аргумента.

options (Объект)

Передайте объект параметров, чтобы изменить поведение по умолчанию .within().

Параметр Значение по умолчанию Описание
log true Отображает команду в журнале команд

Возвращаемое значение

  • .within() возвращает тот же объект, что и предыдущая команда.

Попытка вернуть другой элемент в .within колбеке не повлияет:

<div id="within-yields">
  The parent div
  <div class="some-child">Child element</div>
</div>
cy.get('#within-yields')
  .within(() => {
    // we are trying to return something
    // from the .within callback,
    // but it won't have any effect
    return cy.contains('Child element').should('have.class', 'some-child')
  })
  .should('have.id', 'within-yields')

Аналогично, попытка изменить объект с помощью команды cy.wrap внутри .within колбека не повлияет:

<div id="wrap-inside-within">
  The parent div
  <div class="some-child">Child element</div>
</div>
cy.get('#wrap-inside-within')
  .within(() => {
    // returning cy.wrap(...) has no effect on the yielded value
    // it will still be the original parent DOM element
    return cy.wrap('a new value')
  })
  .should('have.id', 'wrap-inside-within')

Примеры

Формы

Получить поля ввода в форме и отправить форму

<form>
  <input name="email" type="email" />
  <input name="password" type="password" />
  <button type="submit">Login</button>
</form>
cy.get('form').within(($form) => {
  // you have access to the found form via
  // the jQuery object $form if you need it

  // cy.get() will only search for elements within form,
  // not within the entire document
  cy.get('input[name="email"]').type('john.doe@email.com')
  cy.get('input[name="password"]').type('password')
  cy.root().submit()
})

Таблицы

Найти строку с определенной ячейкой и подтвердить другие ячейки в строке

<table>
  <tr>
    <td>My first client</td>
    <td>My first project</td>
    <td>0</td>
    <td>Active</td>
    <td><button>Edit</button></td>
  </tr>
</table>
cy.contains('My first client')
  .parent('tr')
  .within(() => {
    // all searches are automatically rooted to the found tr element
    cy.get('td').eq(1).contains('My first project')
    cy.get('td').eq(2).contains('0')
    cy.get('td').eq(3).contains('Active')
    cy.get('td').eq(4).contains('button', 'Edit').click()
  })

Временное выход

Вы можете временно выйти из контекста .within, начав новую цепочку команд с cy.root, а затем командами .closest.

<section class="example">
  <!-- note the input field outside the form -->
  <input id="name" type="text" />
  <form>
    <input name="email" type="email" />
    <input name="password" type="password" />
    <button type="submit">Login</button>
  </form>
</section>
cy.get('form').within(($form) => {
  // temporarily escape the .within context
  cy.root().closest('.example').find('#name').type('Joe')
  // continue using the .within context
  cy.get('input[name="email"]').type('john.doe@email.com')
  cy.get('input[name="password"]').type('password')
  cy.root().submit()
})

Правила

Требования

  • .within() требует цепочки с предыдущей командой.

Утверждения

  • .within() выполнит утверждения, которые вы прикрепили только один раз, и не будет повторно выполнено.

Таймауты

  • .within() не может иметь таймаут.

Журнал команд

Получить поле ввода в форме

cy.get('.query-form').within((el) => {
  cy.get('input:first')
})

Вышеперечисленные команды будут отображаться в журнале команд как:

Command Log within

При нажатии на команду within в журнале команд, консоль выведет следующее:

Console Log within

История

Версия Изменения
< 0.3.3 Добавлена команда .within()
5.4.0 исправлено значение возвращаемого значения, чтобы оно всегда было родительским элементом

См. также

  • .root()

© 2017 Cypress.io
Licensed under the MIT License.
https://docs.cypress.io/api/commands/within

Spec-Zone.ru

Настройки Оффлайн Что нового Помощь О нас
Spec-Zone .ru
спецификации, руководства, описания, API