Open In App

Cypress - blur() Method

Last Updated : 08 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

When you use the blur() method in Cypress, it's like clicking away from a specific part of a webpage, like an input field. This helps simulate how a real user would interact with the page. It's especially useful when testing websites that do certain things when you focus or unfocus on certain parts of the page.

Usages

The blur() method is commonly used in the following scenarios:

  • To test focus-related events, such as onblur or onfocusout events
  • To simulate user interactions, such as clicking away from an input field
  • To test the behavior of an application when an element loses focus

Syntax

The syntax for the blur() method is as follows:

cy.get(selector).blur()

Where selector is the CSS selector of the element that you want to blur.

Arguments

The blur() method does not take any arguments.

Example 1: Blurring an Input Field

Let's say we have an HTML page with an input field, and we want to test that the input field loses focus when we click away from it.

HTML Code:

HTML
<!DOCTYPE html>
<html>
  <head>
    <title>Blur Example 1</title>
  </head>
  <body>
    <input id="myInput" type="text" />
    <button id="myButton">Click me!</button>
  </body>
</html>

Javascript code:

JavaScript
describe('Blur Example 1', () => {
  it('should blur the input field', () => {
    cy.visit('https://example.com/blur-example-1')
    cy.get('#myInput').focus()
    cy.get('#myButton').click()
    cy.get('#myInput').should('not.be.focused')
  })
})

Output:

Capture3
Output

Example 2: Blurring a Textarea

Let's say we have an HTML page with a textarea, and we want to test that the textarea loses focus when we click away from it.

HTML Code:

HTML
<!DOCTYPE html>
<html>
  <head>
    <title>Blur Example 2</title>
  </head>
  <body>
    <textarea id="myTextarea">Hello, World!</textarea>
    <button id="myButton">Click me!</button>
  </body>
</html>

Javascript code:

JavaScript
describe('Blur Example 2', () => {
  it('should blur the textarea', () => {
    cy.visit('https://example.com/blur-example-2')
    cy.get('#myTextarea').focus()
    cy.get('#myButton').click()
    cy.get('#myTextarea').should('not.be.focused')
  })
})

Output:

Capture4
Output

Conclusion

In short, the blur() method in Cypress is a really helpful tool for testing how a website works when you interact with it like a real user. It helps you make sure that your website does what it's supposed to do when you click away from certain parts of the page.


Next Article

Similar Reads