Replace cy.wait Magic Numbers with forEvent

10/25/20191 Min Read — In Cypress

Magic Numbers. They are an anti-pattern because they are arbitrary and provide no context. This leads to confusion ("What is this number?") and fear of removing it ("I can't remove it. I don't know what it does.").


Looking at this code in isolation, it's impossible to tell what we are waiting for. But this is a contrived example so let's add typical context.


Even with more context, it's still really difficult to guess what we're waiting for. While waiting for an alias is a better and far less error-prone solution, sometimes it doesn't make sense. For example, waiting for an animation to finish.

cy.wait(250) // for animation

The simple fix is to add a comment. This fixes the Magic Number here only. Adding comments on all the cy.wait calls, we will quickly notice a pattern that can be refactored for a huge readability win.

// test.file.js
import { forEvent } from '../helpers'
// helpers/forEvent.js
export const forEvent = {
animation: 250,

By just adding this variable to our helpers, we solve the problems we listed. It's clear what we're waiting for and because of that, if we remove the animation we can remove this line with confidence.


Recall is one of the best ways to optimize learning.

  1. What is a Magic Number? Why is an anti-pattern?
  2. When does it make sense to use cy.wait(time) vs. cy.wait(alias)?
  3. What is one strategy for fixing Magic Numbers?

Discuss on Twitter