Mounting React Components
Learn how to mount React components for Cypress component tests.
We'll cover the following...
Let’s practice mounting our React components and running our first component test. Mounting React components for Cypress component testing means we render them in a Cypress browser test environment, which enables us to test them in isolation. In this lesson, we will mount a component in each test. It’s comparable to visiting a page in end-to-end tests.
Cypress component test script
First, we’ll need to create a new script specifically for running component tests instead of end-to-end tests. In our package.json
file, we make the following change:
import { Button } from "../../src/Button"; describe("button", () => { it("works", () => { cy.mount( <Button disabled={false} onClick={() => undefined} text={"Hello World"} /> ); cy.contains("Hello World"); }); it("disabled works", () => { cy.mount( <Button disabled={true} onClick={() => undefined} text={"Hello World"} /> ); cy.get("button").should("be.disabled"); }); it("onClick handler gets called", () => { const spy = cy.spy().as("spy"); cy.mount(<Button disabled={false} onClick={spy} text={"Hello World"} />); cy.get("button").click(); cy.get("@spy").should("have.been.calledOnce"); }); it("disabling button works", () => { const spy = cy.spy().as("spy"); cy.mount(<Button disabled={true} onClick={spy} text={"Hello World"} />); cy.get("button").click({ force: true }); cy.get("@spy").should("not.have.been.called"); }); }); export {};
Cypress component test script
On line 12, we have a new script called ...