찾다
웹 프론트엔드JS 튜토리얼Cypress에서 동적 드롭다운을 처리하는 방법

How to Handle Dynamic Dropdown in Cypress

Introduction

Handling dynamic dropdowns is a common challenge in modern web applications, especially when dropdown options are fetched dynamically from APIs or loaded based on user interactions. When automating tests for such dropdowns using Cypress, you need to ensure that the right options are selected, even if they are rendered after some delay.

This blog will walk you through the process of interacting with dynamic dropdowns in Cypress and provide examples for common scenarios, including dropdowns populated by API responses and dropdowns that change based on user input.

Why Are Dynamic Dropdowns Challenging?

Dynamic dropdowns often pose testing challenges because:

  • Options are not present initially: The dropdown options may be loaded asynchronously after a user action or API call.
  • Dropdown content changes: Based on user input or interactions, the dropdown options might change dynamically.
  • DOM updates: Cypress needs to wait for the DOM to update before interacting with the dropdown.

Cypress provides several powerful commands to handle these challenges, ensuring that you can select the right option from a dynamic dropdown reliably.

Step-by-Step Guide to Handling Dynamic Dropdowns

Let’s go through a basic example to understand how Cypress can handle dynamic dropdowns.

Step 1: Interact with the Dropdown Trigger
Most dynamic dropdowns are initially hidden and only appear when the user clicks on a button or input field. To begin, you need to interact with the trigger element.

Example HTML:

<select id="country-dropdown">
  <option value="" disabled selected>Select a country</option>
</select>
<button id="load-countries">Load Countries</button>

To simulate user interaction:

it('should click the button to load dropdown options', () => {
  cy.visit('/dropdown-page'); // Visit the page with the dynamic dropdown
  cy.get('#load-countries').click(); // Click the button to load the dropdown options
});

This clicks the button, which in this example triggers an API call or another process to populate the dropdown options dynamically.

Step 2: Wait for the Dropdown to Populate
In dynamic dropdowns, the options may not be available immediately. Cypress can use assertions like should('exist') or wait for elements to become available.

Example of handling the dropdown after population:

it('should wait for dropdown options to be populated', () => {
  cy.get('#country-dropdown').should('exist').click(); // Click to open the dropdown

  // Wait for the dropdown options to populate
  cy.get('#country-dropdown option').should('have.length.greaterThan', 1);
});

Here, Cypress waits until the dropdown options are available before proceeding.

Step 3: Select an Option Dynamically
Once the dropdown is populated, you can select the desired option using cy.select() or by directly interacting with the DOM elements.

Example of selecting a country:

it('should select a country from the dynamic dropdown', () => {
  cy.get('#country-dropdown').select('India'); // Select by visible text
});

If your dropdown doesn't use a native

it('should manually select a country from a custom dropdown', () => {
  cy.get('#country-dropdown').click(); // Open the dropdown

  // Select the desired option by clicking on the visible text
  cy.contains('li', 'India').click(); 
});

Handling Type and Search Dynamic Dropdowns

Many modern applications use a type-and-search dropdown where users type into an input field, and the dropdown options are dynamically filtered based on the entered text. Let’s take a look at how to handle such scenarios in Cypress.

Example Type-and-Search Dynamic Dropdown
Example HTML structure:

<div class="search-dropdown">
  <input type="text" id="search-input" placeholder="Search countries...">
  <ul id="dropdown-options">
    <li>USA</li>
    <li>Canada</li>
    <li>Australia</li>
  </ul>
</div>

In this case, the options in the dropdown are filtered based on the user’s input.

Step 1: Type and Filter Options
When typing into the input field, Cypress can simulate user typing and dynamically filter the options.

it('should filter and select a country from a type-and-search dropdown', () => {
  cy.get('#search-input').type('Can'); // Type into the input field to filter options

  // Verify that the filtered result appears
  cy.get('#dropdown-options li').should('have.length', 1);

  // Verify that the option matches the search term
  cy.get('#dropdown-options li').first().should('contain.text', 'Canada');

  // Click to select the filtered option
  cy.get('#dropdown-options li').first().click();
});

In this case, the options in the dropdown are filtered based on the user’s input.

Step 1: Type and Filter Options
When typing into the input field, Cypress can simulate user typing and dynamically filter the options.

it('should filter and select a country from a type-and-search dropdown', () => {
  cy.get('#search-input').type('Can'); // Type into the input field to filter options

  // Verify that the filtered result appears
  cy.get('#dropdown-options li').should('have.length', 1);

  // Verify that the option matches the search term
  cy.get('#dropdown-options li').first().should('contain.text', 'Canada');

  // Click to select the filtered option
  cy.get('#dropdown-options li').first().click();
});

This code simulates typing Can into the search box, verifies that the dropdown is filtered to show only "Canada," and then selects that option.

Step 2: Wait for Dropdown Options to Load Dynamically (API-driven)
Sometimes, the type-and-search dropdown is backed by an API that returns options based on the user's input. Cypress can wait for the API response and validate the options.

it('should handle type-and-search dropdown populated by API', () => {
  // Intercept the API call triggered by typing
  cy.intercept('GET', '/api/countries?search=Can', {
    fixture: 'filtered-countries.json'  // Mocked API response with filtered data
  }).as('searchCountries');

  // Type into the input to trigger the API call
  cy.get('#search-input').type('Can');

  // Wait for the API response
  cy.wait('@searchCountries');

  // Validate the filtered results
  cy.get('#dropdown-options li').should('have.length', 1);
  cy.get('#dropdown-options li').first().should('contain.text', 'Canada');

  // Select the option
  cy.get('#dropdown-options li').first().click();
});

Here, we use cy.intercept() to intercept and mock the API request that fetches filtered options based on the typed input.

Handling Dropdowns Populated by API Calls

Dynamic dropdowns are often populated by API calls, meaning the data isn't available until the server responds. To handle these dropdowns, Cypress provides cy.intercept() to mock or intercept network calls.

Here’s an example of intercepting an API response and selecting a value from a dynamically populated dropdown:

it('should handle dropdown populated by API', () => {
  // Intercept the API call
  cy.intercept('GET', '/api/countries', { fixture: 'countries.json' }).as('getCountries');

  cy.get('#load-countries').click(); // Trigger the API call

  // Wait for the API call to complete
  cy.wait('@getCountries');

  // Now select an option from the populated dropdown
  cy.get('#country-dropdown').select('Australia');
});

In this case, we use cy.intercept() to mock the /api/countries endpoint and provide a fixture (countries.json) with predefined data. This ensures that the dropdown is populated with the expected values, even in a test environment.

Handling Custom Dropdown Components

Many modern frameworks (like React, Angular, or Vue) use custom dropdown components that don’t use native

Here’s an example with a custom dropdown built using div and li elements:

<div class="dropdown">
  <div class="dropdown-trigger">Select a country</div>
  <ul class="dropdown-options">
    <li>USA</li>
    <li>Canada</li>
    <li>Australia</li>
  </ul>
</div>

Here’s how to interact with this type of custom dropdown in Cypress:

it('should select an option from a custom dropdown', () => {
  cy.get('.dropdown-trigger').click(); // Open the custom dropdown
  cy.contains('.dropdown-options li', 'Canada').click(); // Select the option
});

Best Practices for Handling Dynamic Dropdowns in Cypress

  1. Use Proper Selectors: Always use specific selectors to avoid flaky tests. Prefer data-* attributes or IDs over generic class selectors.

  2. Handle Delays and Dynamic Content: Cypress automatically waits for elements to appear, but you may still need to use .should() or cy.wait() for AJAX-based dropdowns.

  3. Mock API Responses: Use cy.intercept() to mock API calls when testing dropdowns populated by dynamic data.

  4. Check Dropdown State: Ensure you verify both the closed and open states of the dropdown, especially when dealing with custom components.

  5. Avoid Hard-Coding Delays: Instead of using cy.wait(time), leverage cy.intercept() and cy.wait() for API responses to ensure that tests wait for the actual data rather than arbitrary timeouts.

Conclusion

Handling dynamic dropdowns in Cypress doesn’t have to be complicated. With Cypress’s built-in commands like cy.get(), cy.select(), and cy.intercept(), you can easily interact with both native and custom dropdowns, regardless of whether the content is rendered dynamically. By following best practices and using appropriate selectors and waits, you can make your tests more robust, reliable, and maintainable.

Try out these techniques in your Cypress tests to handle dynamic dropdowns effortlessly!

위 내용은 Cypress에서 동적 드롭다운을 처리하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
JavaScript 엔진 : 구현 비교JavaScript 엔진 : 구현 비교Apr 13, 2025 am 12:05 AM

각각의 엔진의 구현 원리 및 최적화 전략이 다르기 때문에 JavaScript 엔진은 JavaScript 코드를 구문 분석하고 실행할 때 다른 영향을 미칩니다. 1. 어휘 분석 : 소스 코드를 어휘 단위로 변환합니다. 2. 문법 분석 : 추상 구문 트리를 생성합니다. 3. 최적화 및 컴파일 : JIT 컴파일러를 통해 기계 코드를 생성합니다. 4. 실행 : 기계 코드를 실행하십시오. V8 엔진은 즉각적인 컴파일 및 숨겨진 클래스를 통해 최적화하여 Spidermonkey는 유형 추론 시스템을 사용하여 동일한 코드에서 성능이 다른 성능을 제공합니다.

브라우저 너머 : 실제 세계의 JavaScript브라우저 너머 : 실제 세계의 JavaScriptApr 12, 2025 am 12:06 AM

실제 세계에서 JavaScript의 응용 프로그램에는 서버 측 프로그래밍, 모바일 애플리케이션 개발 및 사물 인터넷 제어가 포함됩니다. 1. 서버 측 프로그래밍은 Node.js를 통해 실현되며 동시 요청 처리에 적합합니다. 2. 모바일 애플리케이션 개발은 재교육을 통해 수행되며 크로스 플랫폼 배포를 지원합니다. 3. Johnny-Five 라이브러리를 통한 IoT 장치 제어에 사용되며 하드웨어 상호 작용에 적합합니다.

Next.js (백엔드 통합)로 멀티 테넌트 SAAS 애플리케이션 구축Next.js (백엔드 통합)로 멀티 테넌트 SAAS 애플리케이션 구축Apr 11, 2025 am 08:23 AM

일상적인 기술 도구를 사용하여 기능적 다중 테넌트 SaaS 응용 프로그램 (Edtech 앱)을 구축했으며 동일한 작업을 수행 할 수 있습니다. 먼저, 다중 테넌트 SaaS 응용 프로그램은 무엇입니까? 멀티 테넌트 SAAS 응용 프로그램은 노래에서 여러 고객에게 서비스를 제공 할 수 있습니다.

Next.js (Frontend Integration)를 사용하여 멀티 테넌트 SaaS 응용 프로그램을 구축하는 방법Next.js (Frontend Integration)를 사용하여 멀티 테넌트 SaaS 응용 프로그램을 구축하는 방법Apr 11, 2025 am 08:22 AM

이 기사에서는 Contrim에 의해 확보 된 백엔드와의 프론트 엔드 통합을 보여 주며 Next.js를 사용하여 기능적인 Edtech SaaS 응용 프로그램을 구축합니다. Frontend는 UI 가시성을 제어하기 위해 사용자 권한을 가져오고 API가 역할 기반을 준수하도록합니다.

JavaScript : 웹 언어의 다양성 탐색JavaScript : 웹 언어의 다양성 탐색Apr 11, 2025 am 12:01 AM

JavaScript는 현대 웹 개발의 핵심 언어이며 다양성과 유연성에 널리 사용됩니다. 1) 프론트 엔드 개발 : DOM 운영 및 최신 프레임 워크 (예 : React, Vue.js, Angular)를 통해 동적 웹 페이지 및 단일 페이지 응용 프로그램을 구축합니다. 2) 서버 측 개발 : Node.js는 비 차단 I/O 모델을 사용하여 높은 동시성 및 실시간 응용 프로그램을 처리합니다. 3) 모바일 및 데스크탑 애플리케이션 개발 : 크로스 플랫폼 개발은 개발 효율을 향상시키기 위해 반응 및 전자를 통해 실현됩니다.

JavaScript의 진화 : 현재 동향과 미래 전망JavaScript의 진화 : 현재 동향과 미래 전망Apr 10, 2025 am 09:33 AM

JavaScript의 최신 트렌드에는 Typescript의 Rise, 현대 프레임 워크 및 라이브러리의 인기 및 WebAssembly의 적용이 포함됩니다. 향후 전망은보다 강력한 유형 시스템, 서버 측 JavaScript 개발, 인공 지능 및 기계 학습의 확장, IoT 및 Edge 컴퓨팅의 잠재력을 포함합니다.

Demystifying JavaScript : 그것이하는 일과 중요한 이유Demystifying JavaScript : 그것이하는 일과 중요한 이유Apr 09, 2025 am 12:07 AM

JavaScript는 현대 웹 개발의 초석이며 주요 기능에는 이벤트 중심 프로그래밍, 동적 컨텐츠 생성 및 비동기 프로그래밍이 포함됩니다. 1) 이벤트 중심 프로그래밍을 사용하면 사용자 작업에 따라 웹 페이지가 동적으로 변경 될 수 있습니다. 2) 동적 컨텐츠 생성을 사용하면 조건에 따라 페이지 컨텐츠를 조정할 수 있습니다. 3) 비동기 프로그래밍은 사용자 인터페이스가 차단되지 않도록합니다. JavaScript는 웹 상호 작용, 단일 페이지 응용 프로그램 및 서버 측 개발에 널리 사용되며 사용자 경험 및 크로스 플랫폼 개발의 유연성을 크게 향상시킵니다.

Python 또는 JavaScript가 더 좋습니까?Python 또는 JavaScript가 더 좋습니까?Apr 06, 2025 am 12:14 AM

Python은 데이터 과학 및 기계 학습에 더 적합한 반면 JavaScript는 프론트 엔드 및 풀 스택 개발에 더 적합합니다. 1. Python은 간결한 구문 및 풍부한 라이브러리 생태계로 유명하며 데이터 분석 및 웹 개발에 적합합니다. 2. JavaScript는 프론트 엔드 개발의 핵심입니다. Node.js는 서버 측 프로그래밍을 지원하며 풀 스택 개발에 적합합니다.

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25 : Myrise에서 모든 것을 잠금 해제하는 방법
4 몇 주 전By尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

맨티스BT

맨티스BT

Mantis는 제품 결함 추적을 돕기 위해 설계된 배포하기 쉬운 웹 기반 결함 추적 도구입니다. PHP, MySQL 및 웹 서버가 필요합니다. 데모 및 호스팅 서비스를 확인해 보세요.

MinGW - Windows용 미니멀리스트 GNU

MinGW - Windows용 미니멀리스트 GNU

이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.

ZendStudio 13.5.1 맥

ZendStudio 13.5.1 맥

강력한 PHP 통합 개발 환경

에디트플러스 중국어 크랙 버전

에디트플러스 중국어 크랙 버전

작은 크기, 구문 강조, 코드 프롬프트 기능을 지원하지 않음

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경