Home > Back-end >  Cypress - test nothing happen
Cypress - test nothing happen

Time:09-26

I have a button "Go Google" and an input box.

When there is content in the input box, clicking the button will open a new tab for users to navigate another website. Otherwise, clicking the button will trigger nothing.

App.tsx

import "./styles.css";
import React, { useState } from "react";

export default function App() {
  const [input, setInput] = useState("");

  const onButtonClick = () => {
    if (input !== "") {
      window.open("www.google.com");
    }
  };

  return (
    <div className="App">
      <input value={input} onChange={(e) => setInput(e.target.value)} />
      <button onClick={onButtonClick}>Go Google</button>
    </div>
  );
}

How can I write the test case using Cypress to test here is nothing happen when the button is clicked in Cypress?

Codesandbox
https://codesandbox.io/s/react-typescript-forked-vovdht?file=/src/App.tsx:0-430

CodePudding user response:

You can stub the window object and alias it. That way you can check if it's called or not.

Also you can add the data-cy to the test subject so that you can have a dedicated selector only for testing.


      <button onClick={onButtonClick} data-cy="google-btn">Go Google</button>

describe('When button is clicked', () => {
    it('does not open a new window', function () {
        cy.window().then((win) => {
            cy.stub(win, 'open', url => {
                win.location.href = url;
            }).as("wndopen")
        })
        cy.get('[data-cy="google-btn"]').click()
        cy.get('@wndopen')
            .should("not.be.called")
    })
})
  • Related