Cypress tests often become flaky when developers assume cy.wait('@alias') waits for every new request. It doesn’t. Aliases capture only the first match, so later waits may resolve instantly. The fix: re-intercept before each occurrence or use times: 1 to create one-shot intercepts that “consume” themselves. But the real solution is avoiding network waits altogether. Instead, rely on user-visible, accessible UI states (spinners, aria-busy, disabled buttons, status messages). This makes tests stable, realistic, and far more reliable than waiting on network events.Cypress tests often become flaky when developers assume cy.wait('@alias') waits for every new request. It doesn’t. Aliases capture only the first match, so later waits may resolve instantly. The fix: re-intercept before each occurrence or use times: 1 to create one-shot intercepts that “consume” themselves. But the real solution is avoiding network waits altogether. Instead, rely on user-visible, accessible UI states (spinners, aria-busy, disabled buttons, status messages). This makes tests stable, realistic, and far more reliable than waiting on network events.

Achieving Reliable E2E Tests in Cypress: Overcome cy.wait Pitfalls

2025/11/26 13:14

Cypress gives frontend engineers a superpower: the ability to write E2E tests that watch our app behave just like a real user would. But with great power comes… well, a lot of subtle flakiness if you’re not careful.

The cy.wait Illusion: What's Really Happening

The scenario is simple: you have a component that loads data, and after a user action, it loads new data using the same API endpoint. To ensure the new data has arrived, you intercept the request and then use cy.wait('@requestAlias') multiple times.

// A common, flawed approach: cy.intercept('GET', '/api/items/*', { fixture: 'item-1' }).as('getItems'); cy.visit('/items'); // 1. Wait for the initial load cy.wait('@getItems'); // ... User performs an action that triggers the SAME request ... // 2. Wait for the second load cy.wait('@getItems'); // <-- THIS IS THE PROBLEM

The Flaw

Cypress's cy.intercept logic is designed to capture a single match for an alias. When you call cy.wait('@getItems') for the first time, it finds the initial request, waits for its resolution, and then the alias is fulfilled.

When you call cy.wait('@getItems') a second time, Cypress does not reset the listener. Instead, it checks if a request has already been resolved with that alias. Because the first request has resolved, the second cy.wait command resolves immediately, without waiting for the new network call to finish. Your test is now racing against the network, not waiting for it.

Fix #1: Re-intercept before each expected request

(Works, explicit, but verbose)

cy.intercept('GET', '/api/items').as('getItems_1') cy.get('[data-testid=refresh]').click() cy.wait('@getItems_1') cy.intercept('GET', '/api/items').as('getItems_2') cy.get('[data-testid=load-more]').click() cy.wait('@getItems_2')

Clear, deterministic, but repetitive.

Fix #2: Use times: 1 to force Cypress to “consume” intercepts

(Cleaner: Cypress forgets the intercept after one match)

This is the missing tool many engineers don’t realize exists.

cy.intercept({ method: 'GET', pathname: '/api/items', times: 1 }).as('getItems') // trigger request 1 cy.get('[data-testid=refresh]').click() cy.wait('@getItems') cy.intercept({ method: 'GET', pathname: '/api/items', times: 1 }).as('getItems') // trigger request 2 cy.get('[data-testid=load-more]').click() cy.wait('@getItems')

Why this works:

  • times: 1 means Cypress removes the intercept after a single matching request
  • Re-declaring the intercept creates a fresh listener
  • Each cy.wait('@getItems') now truly waits for the next occurrence

This technique gives you explicit, occurrence-specific intercepts without alias clutter. For tests that must assert network behavior (payloads, headers, error flows), it’s a clean and robust pattern.

Fix #3: Stop waiting for requests altogether

(The best fix. UI > network.)

Here’s the golden rule:

That means the most stable tests assert what the user sees:

  • A loading spinner appears → disappears
  • A button becomes disabled → enabled
  • A success message appears when an action is complete.
  • The newly loaded element is now visible in the DOM.

Example with user-visible cues:

cy.get('[data-testid=refresh]').click() cy.get('[data-testid=spinner]').should('exist') cy.get('[data-testid=spinner]').should('not.exist') cy.get('[data-testid=item-list]') .children() .should('have.length.at.least', 1)

No reliance on internal network timing. No alias lifecycle. Zero flake.

Accessibility makes this even more robust

Accessible UI patterns make great Cypress hooks:

aria-busy attribute

<ul data-testid="item-list" aria-busy="true">

Test:

cy.get('[data-testid=item-list]').should('have.attr', 'aria-busy', 'false')

role="status" with live regions

<div role="status" aria-live="polite" data-testid="status"> Loading… </div>

Test:

cy.get('[data-testid=status]').should('contain', 'Loaded 10 items')

Disabled states for actions

cy.get('[data-testid=submit]').should('be.disabled') cy.get('[data-testid=submit]').should('not.be.disabled')

These patterns aid screen reader users and produce stable, deterministic E2E tests.

When waiting for requests is appropriate

There ARE valid scenarios:

  • Asserting payloads or query params
  • Mocking backend responses
  • Validating request ordering
  • Verifying retry logic
  • Testing error handling flows

For those cases: Combine times: 1 with explicit, fresh intercepts defined right before triggers.

For other cases: the test should rely on the UI state.

A combined real-world example

(Network + UI, the best of both worlds)

// UI-driven loading signal cy.get('[data-testid=create]').click() cy.get('[data-testid=spinner]').should('exist') // Network contract check cy.intercept({ method: 'POST', pathname: '/api/items', times: 1 }).as('postItem') cy.get('[data-testid=create]').click() cy.wait('@postItem') .its('request.body') .should('deep.include', { title: 'New item' }) // Final user-visible assertion cy.get('[data-testid=status]').should('contain', 'Item created')

The network part is accurate. The UI part is resilient. The test is rock-solid.

Final checklist

For accessible, deterministic, non-flaky Cypress tests

  • Prefer user-visible UI state, not network events
  • Use aria-busy, role="status", aria-live, and disabled states
  • When waiting for requests:
  • Re-intercept before each occurrence, OR
  • Use times: 1 to auto-expire the intercept
  • Avoid global, long-lived intercepts
  • Never assume cy.wait('@alias') waits “for the next request”
  • Make loading and completion states accessible (good for tests, good for users)

\

Sorumluluk Reddi: Bu sitede yeniden yayınlanan makaleler, halka açık platformlardan alınmıştır ve yalnızca bilgilendirme amaçlıdır. MEXC'nin görüşlerini yansıtmayabilir. Tüm hakları telif sahiplerine aittir. Herhangi bir içeriğin üçüncü taraf haklarını ihlal ettiğini düşünüyorsanız, kaldırılması için lütfen [email protected] ile iletişime geçin. MEXC, içeriğin doğruluğu, eksiksizliği veya güncelliği konusunda hiçbir garanti vermez ve sağlanan bilgilere dayalı olarak alınan herhangi bir eylemden sorumlu değildir. İçerik, finansal, yasal veya diğer profesyonel tavsiye niteliğinde değildir ve MEXC tarafından bir tavsiye veya onay olarak değerlendirilmemelidir.

Ayrıca Şunları da Beğenebilirsiniz

Wormhole Unveils W Token 2.0 with Enhanced Tokenomics

Wormhole Unveils W Token 2.0 with Enhanced Tokenomics

The post Wormhole Unveils W Token 2.0 with Enhanced Tokenomics appeared on BitcoinEthereumNews.com. Joerg Hiller Sep 17, 2025 13:57 Wormhole introduces W Token 2.0, featuring upgraded tokenomics, a strategic Wormhole Reserve, and a 4% base yield, aiming to optimize ecosystem growth and align incentives. Wormhole has announced a significant upgrade to its native token, unveiling the W Token 2.0. This upgrade introduces new tokenomics including the establishment of a Wormhole Reserve, a 4% base yield, and an optimized unlock schedule, marking a pivotal development in the ecosystem, according to Wormhole. The W Token Evolution Launched in October 2020, Wormhole’s W token has been central to the platform’s mission of creating a connected internet economy. The latest upgrade aims to enhance the token’s utility across more than 40 blockchains. With a capped supply of 10 billion, the W token supports governance, staking, and ecosystem growth, aligning incentives for network security and development. Introducing the Wormhole Reserve The Wormhole Reserve will accumulate value from both onchain and offchain activities, supporting the ecosystem’s expansion. As Wormhole adoption grows, the token will capture value through network expansions and ecosystem applications, ensuring that growth is directly reflected in the token’s value. 4% Base Yield and Governance Rewards Wormhole 2.0 introduces a 4% base yield for W holders who actively participate in governance. The yield, derived from existing token supplies and protocol revenues, is designed to incentivize active participation without inflating the token supply. Optimized Unlock Schedule Updating its token release schedule, Wormhole replaces annual cliffs with bi-weekly unlocks, starting October 3, 2025. This change aims to reduce market pressure and provide a more stable environment for investors and contributors. The bi-weekly schedule will span over 4.5 years, affecting categories such as Guardian Nodes and Community & Launch. Wormhole’s Future Vision With these upgrades, Wormhole aims to expand its role as…
Paylaş
BitcoinEthereumNews2025/09/18 15:48
[OPINION] US National Security Strategy 2025: An iconoclastic document

[OPINION] US National Security Strategy 2025: An iconoclastic document

Trump's national security strategy signals a radical shift in US foreign policy, prioritizing economic power and regional interests over global commitments
Paylaş
Rappler2025/12/16 12:30
Crucial US Stock Market Update: What Wednesday’s Mixed Close Reveals

Crucial US Stock Market Update: What Wednesday’s Mixed Close Reveals

BitcoinWorld Crucial US Stock Market Update: What Wednesday’s Mixed Close Reveals The financial world often keeps us on our toes, and Wednesday was no exception. Investors watched closely as the US stock market concluded the day with a mixed performance across its major indexes. This snapshot offers a crucial glimpse into current investor sentiment and economic undercurrents, prompting many to ask: what exactly happened? Understanding the Latest US Stock Market Movements On Wednesday, the closing bell brought a varied picture for the US stock market. While some indexes celebrated gains, others registered slight declines, creating a truly mixed bag for investors. The Dow Jones Industrial Average showed resilience, climbing by a notable 0.57%. This positive movement suggests strength in some of the larger, more established companies. Conversely, the S&P 500, a broader benchmark often seen as a barometer for the overall market, experienced a modest dip of 0.1%. The technology-heavy Nasdaq Composite also saw a slight retreat, sliding by 0.33%. This particular index often reflects investor sentiment towards growth stocks and the tech sector. These divergent outcomes highlight the complex dynamics currently at play within the American economy. It’s not simply a matter of “up” or “down” for the entire US stock market; rather, it’s a nuanced landscape where different sectors and company types are responding to unique pressures and opportunities. Why Did the US Stock Market See Mixed Results? When the US stock market delivers a mixed performance, it often points to a tug-of-war between various economic factors. Several elements could have contributed to Wednesday’s varied closings. For instance, positive corporate earnings reports from certain industries might have bolstered the Dow. At the same time, concerns over inflation, interest rate policies by the Federal Reserve, or even global economic uncertainties could have pressured growth stocks, affecting the S&P 500 and Nasdaq. Key considerations often include: Economic Data: Recent reports on employment, manufacturing, or consumer spending can sway market sentiment. Corporate Announcements: Strong or weak earnings forecasts from influential companies can significantly impact their respective sectors. Interest Rate Expectations: The prospect of higher or lower interest rates directly influences borrowing costs for businesses and consumer spending, affecting future profitability. Geopolitical Events: Global tensions or trade policies can introduce uncertainty, causing investors to become more cautious. Understanding these underlying drivers is crucial for anyone trying to make sense of daily market fluctuations in the US stock market. Navigating Volatility in the US Stock Market A mixed close, while not a dramatic downturn, serves as a reminder that market volatility is a constant companion for investors. For those involved in the US stock market, particularly individuals managing their portfolios, these days underscore the importance of a well-thought-out strategy. It’s important not to react impulsively to daily movements. Instead, consider these actionable insights: Diversification: Spreading investments across different sectors and asset classes can help mitigate risk when one area underperforms. Long-Term Perspective: Focusing on long-term financial goals rather than short-term gains can help weather daily market swings. Stay Informed: Keeping abreast of economic news and company fundamentals provides context for market behavior. Consult Experts: Financial advisors can offer personalized guidance based on individual risk tolerance and objectives. Even small movements in major indexes can signal shifts that require attention, guiding future investment decisions within the dynamic US stock market. What’s Next for the US Stock Market? Looking ahead, investors will be keenly watching for further economic indicators and corporate announcements to gauge the direction of the US stock market. Upcoming inflation data, statements from the Federal Reserve, and quarterly earnings reports will likely provide more clarity. The interplay of these factors will continue to shape investor confidence and, consequently, the performance of the Dow, S&P 500, and Nasdaq. Remaining informed and adaptive will be key to understanding the market’s trajectory. Conclusion: Wednesday’s mixed close in the US stock market highlights the intricate balance of forces influencing financial markets. While the Dow showed strength, the S&P 500 and Nasdaq experienced slight declines, reflecting a nuanced economic landscape. This reminds us that understanding the ‘why’ behind these movements is as important as the movements themselves. As always, a thoughtful, informed approach remains the best strategy for navigating the complexities of the market. Frequently Asked Questions (FAQs) Q1: What does a “mixed close” mean for the US stock market? A1: A mixed close indicates that while some major stock indexes advanced, others declined. It suggests that different sectors or types of companies within the US stock market are experiencing varying influences, rather than a uniform market movement. Q2: Which major indexes were affected on Wednesday? A2: On Wednesday, the Dow Jones Industrial Average gained 0.57%, while the S&P 500 edged down 0.1%, and the Nasdaq Composite slid 0.33%, illustrating the mixed performance across the US stock market. Q3: What factors contribute to a mixed stock market performance? A3: Mixed performances in the US stock market can be influenced by various factors, including specific corporate earnings, economic data releases, shifts in interest rate expectations, and broader geopolitical events that affect different market segments uniquely. Q4: How should investors react to mixed market signals? A4: Investors are generally advised to maintain a long-term perspective, diversify their portfolios, stay informed about economic news, and avoid impulsive decisions. Consulting a financial advisor can also provide personalized guidance for navigating the US stock market. Q5: What indicators should investors watch for future US stock market trends? A5: Key indicators to watch include upcoming inflation reports, statements from the Federal Reserve regarding monetary policy, and quarterly corporate earnings reports. These will offer insights into the future direction of the US stock market. Did you find this analysis of the US stock market helpful? Share this article with your network on social media to help others understand the nuances of current financial trends! To learn more about the latest stock market trends, explore our article on key developments shaping the US stock market‘s future performance. This post Crucial US Stock Market Update: What Wednesday’s Mixed Close Reveals first appeared on BitcoinWorld.
Paylaş
Coinstats2025/09/18 05:30