When Can The Test Blink? (2024)

Let's take a page where a loading element is displayed while the application is fetching the data from the server. If the test is observing the loading element to make sure it disappears, can the loading be too fast? Can the test runner "blink" and miss the element?

Yes, it can. In this blog post I will show an example of a flaky test where this happens. You can find the source code for this post in the repository bahmutov/cypress-blink-example.

The loading element test

Let's write a test to visit the local web application, ensure the loading element appears, then disappears. The test finishes by checking the expected number of items is present on the page.

describe('TodoMVC App', () => { it('shows loading element', () => { cy.visit('/?delay=500') cy.get('.loading').should('be.visible') cy.get('.loading').should('not.be.visible') cy.get('li.todo').should('have.length', 2) })})

The test above first uses the positive assertion .should('be.visible') to establish the element is displayed, then the negative assertion .should('not.be.visible') to make sure the element goes away. We need the positive assertion first to make sure the test does not pass before the application starts data load. For more on negative assertions read the blog post Be Careful With Negative Assertions.

Note: the example application delays the data fetching if there is the ?delay=N URL parameter. This makes the test easier to explain and understand.

When Can The Test Blink? (1)

The test passes, but once in a while we see it fail, and sometimes it fails on continuous integration service. The video below shows the test pass, then fail when I click the "R" key to re-run the tests.

When Can The Test Blink? (2)

What is going on?

Run the test multiple times

First, let's make the test fail faster. The loading element should become visible after at most 500ms, thus there is no point to wait for 4 seconds (the default command timeout) before the test fails.

describe('TodoMVC App', () => { it('shows loading element', () => { cy.visit('/?delay=500') cy.get('.loading', { timeout: 800 }).should('be.visible') cy.get('.loading').should('not.be.visible') cy.get('li.todo').should('have.length', 2) })})

Now let us see how often the test fails. We can run the test N times to see the failure rate. I will use the bundled Lodash to repeat the callback function N times to define N tests.

describe('TodoMVC App', () => { Cypress._.times(20, (k) => { it(`shows loading element ${k}`, () => { cy.visit('/?delay=500') cy.get('.loading', { timeout: 800 }).should('be.visible') cy.get('.loading').should('not.be.visible') cy.get('li.todo').should('have.length', 2) }) })})

The 20 tests run and fail 7 times = about 1/3 failure rate!

When Can The Test Blink? (3)

Typically, if the rate is very low, I would enable test retries and call it a day. But in our case the test has a fundamental flaw that we should not "overlook" by retrying.

It is the loading speed

If we observe a passing test we can see the loading element appearing and disappearing very quickly. Let us time how long it takes to fetch JSON data from the server. I will modify the application's code, and the elapsed time will be printed in the console.

loadTodos({ commit, state }) { console.log('loadTodos start, delay is %d', state.delay) setTimeout(() => { commit('SET_LOADING', true) const loadingStarted = Number(new Date()) axios .get('/todos') .then(r => r.data) .then(todos => { commit('SET_TODOS', todos) commit('SET_LOADING', false) const loadingStopped = Number(new Date()) const loadingTook = loadingStopped - loadingStarted console.log('>>>loading took', loadingTook) }) .catch(e => { console.error('could not load todos') console.error(e.message) console.error(e.response.data) }) }, state.delay)},

I will also add a console statement at the start of the test

it(`shows loading element ${k}`, () => { console.log('>>>test', k) cy.visit('/?delay=500') ...})

Let's run the test - we can filter the console logs using ">>>" string to show the test index and the loading duration messages only.

When Can The Test Blink? (4)

Notice a curious thing: every failed test had the loading durations of just 15-16ms, while every successful test had the loading durations of longer than 24ms. Could the test runner be fooled by the fast sequence of the element appearing and disappearing?

To verify the minimum loading duration the application can have without failing the test, let's just return a mock data from the application after a certain delay, without actually fetching the data from the server.

setTimeout(() => { const todos = [ { id: '1', title: 'first' }, { id: '2', title: 'second' }, ] commit('SET_TODOS', todos) commit('SET_LOADING', false) const loadingStopped = Number(new Date()) const loadingTook = loadingStopped - loadingStarted console.log('>>>loading took', loadingTook)}, 10)

The majority of tests now have a loading time of below 15ms, and are thus failing (of course any JavaScript timer set below 15 ms might take longer, thus there are still passing tests when the event loop was busy, and callback ran after longer period)

When Can The Test Blink? (5)

If we slow down the loading on the other hand, the tests reliably pass. The timeout of 20ms makes the tests solid green.

When Can The Test Blink? (6)

Test retries speed

When a Cypress test retries a command plus assertion combination, how quick is it? When the test checks for the loading element to be visible - how often does the assertion run? Let's find out.

Instead of cy.get('.loading').should('be.visible') let's run a .should(cb) assertion and measure the elapsed time between the callback execution timestamps.

it(`shows loading element ${k}`, () => { console.log('>>>test', k) cy.visit('/?delay=500') let previous = Number(new Date()) cy.get('.loading', { timeout: 800 }).should(($el) => { const current = Number(new Date()) const elapsed = current - previous console.log('>>>should', elapsed) previous = current expect($el).to.be.visible }) cy.get('.loading').should('not.be.visible') cy.get('li.todo').should('have.length', 2)})

Running the tests shows about 21+ ms between the assertion callback function executions.

When Can The Test Blink? (7)

Thus any DOM element that appears and disappears between 21ms intervals can become invisible to the test. Blink and you miss it!

Aside from the failing test, the elements that are too quick can also be invisible in the video of the test run. After all, a standard 30 frames per second video has video frames spaced 33ms apart.

Fixing the test

Let's fix our test - and not by modifying the application's code, but by slowing down the network request to reliably see the loading indicator. Notice that we need to slow down the loading request in this test only because other tests we might have do not look for the loading indicator, and thus do not care about its speed.

I will use the cy.intercept command to return a fixture file, delayed by a few hundred milliseconds. This should make the application consistently show the loading element.

it(`shows loading element ${k}`, () => { console.log('>>>test', k) cy.intercept('/todos', { fixture: 'todos.json', delayMs: 1000, }) cy.visit('/?delay=500') cy.get('.loading', { timeout: 800 }).should('be.visible') cy.get('.loading').should('not.be.visible') cy.get('li.todo').should('have.length', 2)})

As you can see from the end of the test run, all tests are green, and all is good in the world.

When Can The Test Blink? (8)

Happy testing!

Read more

When Can The Test Blink? (2024)

FAQs

How do I know if I blink enough? ›

If you take a moment to tally your blinks over a minute without altering your natural rhythm, you'll likely find that an adult blinks between ten to twenty times each minute, with each blink lasting only about a tenth of a second.

What happens if I don't blink enough? ›

And without blinking (you guessed it), you're more likely to develop dry eyes, tension headaches, and even eye infections. To help prevent this, make sure you give your eyes (and your mind) a break every 20 minutes. Just look away from the screen for 10 seconds and focus on something else.

What is the response time of the eye blink? ›

The reflex occurs at a rapid rate of 0.1 seconds. The purpose of this reflex is to protect the eyes from foreign bodies and bright lights (the latter known as the optical reflex). The blink reflex also occurs when sounds greater than 40–60 dB are made.

What happens if you don't blink for 12 days? ›

What happens if you don't blink? If you don't blink often enough, it can cause problems such as dry eyes. Dry eye symptoms may include: Blurry vision.

Do blinking exercises unblock meibomian glands? ›

Medical professionals often associate incomplete blinking with an increased risk of MGD. This suggests that blinking exercises may be an effective treatment for MGD. However, more research is necessary to determine whether blinking exercises can help unblock meibomian glands.

Does exercise help blepharitis? ›

These lifestyle adjustments can be helpful for people who experience blepharitis and need to manage their condition. Avoiding smoking, alcohol, and caffeine can increase skin health to reduce any debris buildup. In the opposite but complementary way, exercise and nutrition can promote healthy skin.

How to train to blink more? ›

Blinking Exercises
  1. Gently close the eyes fully – count 1,2.
  2. Squeeze the lids together – count 1,2.
  3. Open the eyes – count 1,2.
  4. Repeat the exercise 5 times.

What happens if you don't blink for 8 hours? ›

But if you don't blink, the lack of oxygen can lead to corneal swelling. In fact, your cornea even swells a little bit when you sleep, but goes back to normal soon after you wake up. Your eyes won't get the nutrients they need to stay healthy. Your eyes can dry out, because your tear film isn't being replenished.

What happens if you don't blink for 20 seconds? ›

Without blinking, you'd have dry, uncomfortable or painful eyes. You also wouldn't be able to see as clearly, and you'd have a much higher risk of eye infections. Blinking keeps your eyes healthy in many ways.

What is the normal eye blink time? ›

The levator palpebrae superioris' action is sent through the oculomotor nerve. The duration of a blink is on average 100–150 milliseconds according to UCL researcher and between 100 and 400 ms according to the Harvard Database of Useful Biological Numbers. Closures in excess of 1000 ms were defined as microsleeps.

Why do some people blink less? ›

Several studies have found that the rate at which we spontaneously blink mirrors the neurotransmitter's activity in our brains — the lower the dopamine, the more we fixate on one subject, and the less frequently we blink.

How many seconds should you blink? ›

Making a conscious effort to blink every 10 to 15 seconds will keep your vision sharper while you work and prevent your eyes from feeling as strained at the end of your work.

How long can a person stare without blinking? ›

How long can one go without blinking? Well normally we blink about 15–16 times in a minute, as this is involuntary. I am guessing that one can hold up to 20–30 seconds without blinking. However, staring contests hold records of up to 30–40 mins of going without blinking.

Why can I only wink with one eye? ›

Most people have a preferred winking eye. Others can wink only with one. And some find it hard to wink at all. Scientists note that human beings have many such "asymmetries." Depending on what we're doing, one side of the body is more dominant or responsive.

What is the normal amount to blink? ›

On average, most people blink 15 to 20 times per minute. This helps your eyes stay healthy by keeping them oxygenated and moist, and clearing out debris. While there are some conditions that can cause you to blink more or less frequently, a change in your rate of blinking is rarely a sign of a serious issue.

Can you train yourself to blink more? ›

To try blinking exercises, set a timer for 1 minute at a time and blink your eyes for up to 50 times in several directions (up and down). You can repeat this process up to five times per day. Rather than shutting your eyes completely during blinking exercises, make sure your eyes rapidly flutter closed and open.

What does it mean when you barely blink? ›

Environmental Factors: Environmental conditions can also affect blinking habits. Dry or dusty air can make the eyes more prone to discomfort, causing individuals to not blink enough to avoid aggravating them. 4. Stress and Fatigue: Stress and fatigue can also be why you're not blinking enough.

References

Top Articles
Latest Posts
Article information

Author: Kareem Mueller DO

Last Updated:

Views: 5757

Rating: 4.6 / 5 (66 voted)

Reviews: 89% of readers found this page helpful

Author information

Name: Kareem Mueller DO

Birthday: 1997-01-04

Address: Apt. 156 12935 Runolfsdottir Mission, Greenfort, MN 74384-6749

Phone: +16704982844747

Job: Corporate Administration Planner

Hobby: Mountain biking, Jewelry making, Stone skipping, Lacemaking, Knife making, Scrapbooking, Letterboxing

Introduction: My name is Kareem Mueller DO, I am a vivacious, super, thoughtful, excited, handsome, beautiful, combative person who loves writing and wants to share my knowledge and understanding with you.