Mounting Components In Cypress

Hello Fellow Developers, hope you guys are doing fine 😉

In this Blog we are going to learn what is a  mount function

Create a stepper component first before starting the following

import { useState } from 'react'

export default function Stepper({ initial = 0 }) {
  const [count, setCount] = useState(initial)

  return (
    <div>
      <button aria-label="decrement" onClick={() => setCount(count - 1)}>
        -
      </button>
      <span data-cy="counter">{count}</span>
      <button aria-label="increment" onClick={() => setCount(count + 1)}>
        +
      </button>
    </div>
  )
}

Now lets get started

We ship a Mount function for each front-end framework that Cypress supports, which is imported from the cypress  package. It is responsible to render components within Cypress’s sandboxed iframes and handling and framework-specific cleanup.

// React 16, 17
import { mount } from 'cypress/react'

// React 18
import { mount } from 'cypress/react18'

While you can use the mount function in your tests, we recommend using cy.mount(), which is added as a custom command  in the cypress/support/component.js file:

import { mount } from 'cypress/react'

Cypress.Commands.add('mount', mount)

Now it’s time to see test in action. Open  Cypress if it is not already running:

npx cypress open --component

Launch the browser of your choice. In the spec list, click on stepper.cy.js and you will see the stepper component mounted in test area.

A basic test that mount a component in its default state is an excellent way to start test. Since Cypress render your component in a real browser, you have a lot of advantage, such as seeing that the component render as it should, interacting with the components in the test runner, and using the browser dev tools to inspect and debug both your test and the component’s code.

Feel free to play around with the Stepper component by interacting with the increment and decrement buttons.

That’s it for this blog feel free to contact me in comment section if you have any doubts or questions regarding the same

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories