簡體   English   中英

賽普拉斯 - 測試沒有任何反應

[英]Cypress - test nothing happen

我有一個“Go Google”按鈕和一個輸入框。

當輸入框中有內容時,單擊該按鈕將打開一個新選項卡,供用戶瀏覽另一個網站。 否則,單擊按鈕將不會觸發任何內容。

應用程序.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>
  );
}

如何使用 Cypress 編寫測試用例進行測試,在 Cypress 中單擊按鈕時沒有任何反應?

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

您可以存根window object 並為其命名。 這樣你就可以檢查它是否被調用。

您還可以data-cy添加到測試主題,以便您可以擁有一個僅用於測試的專用選擇器。


      <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")
    })
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM