簡體   English   中英

帶有 jest 和 react-testing-library 的測試方法

[英]test method with jest and react-testing-library

我無法得到答案,如何無法使用 jest 和 react-testing-library 達到功能組件內部的方法。

我嘗試使用酶,但我看到一切都在改變為 RTL。

import React from "react";

const simpleComponents = (props) => {

    const simpleMethod = () =>{ 
        // method logic
    };

    return <h1>test</h1>;
    };
}

export default simpleComponents;

您應該嘗試只測試您的用戶在真實瀏覽器中看到的內容,而不是您的組件內部邏輯。 這就是 react-testing-library 所提倡的:編寫能夠給人信心的測試,因為他們看到/做真實用戶會做的事情。

https://testing-library.com/docs/guiding-principles

遵循這些准則,您應該嘗試構建一個測試來觸發可見元素(由您的組件呈現)上的用戶交互,並且這將涉及執行 simpleMethod。

這就是 react-testing-library 查詢的重點:getByText、getByPlaceholder、getByRole:真實用戶會看到的東西,隱藏了內部邏輯。 但我想你可以用酶來做這種方法(我從來沒有用過酶)。

使用這種方法編寫測試會導致測試更少,但測試更強,恕我直言,這是一件好事。 它與測試函數、輸入、輸出的經典單元測試(例如在 Java 上下文中)完全不同......

事實上,你的 React 組件是一個 function,它的輸入是用戶交互,它的 output 是一個 DOM。

simpleMethod function 在simpleComponents SFC 的私有 scope 中定義。 它沒有暴露,因此您無法在simpleComponents之外獲得 function 。

但是你可以間接測試它,例如:

const simpleMethod = () =>{ 
  console.log('method logic');
};

首先,您需要使用諸如click , submit之類的事件來觸發它。 我們添加了一個console.log方法,所以我們可以窺探console.log方法,檢查是否調用了simpleMethod function。

暫無
暫無

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

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