[英]Question about testing React components using CustomHooks
我剛剛開始學習 React 和 Redux。 有一個關於如何在 Jest 中測試的問題。
我將組件邏輯與功能組件分離為 CustomHooks,並在與定義組件的文件不同的文件中實現它們。 在 CustomHooks 中,它使用useState
和useDispatch
鈎子。
・src/components/counter.tsx
import React from 'react';
import { useCounter } from 'modules/counter/operators';
const Counter: React.FC = () => {
const { count, total, handleIncrementClick, handleResetClick } = useCounter();
return (
<div>
<p>total:{total}</p>
<p>current:{count}</p>
<button onClinc={handleIncrementClick}>Increment</button>
<button onClinc={handleResetClick}>Reset</button>
</div>
);
};
・src/modules/counter/operators.ts
import { useState, useCallback, MouseEvent } from 'react';
import { useDispatch } from 'react-redux';
import { counterActions } from 'modules/counter/slicer';
const useCounter = (): [
string,
(e: MouseEvent) => void,
(e: MouseEvent) => void,
] => {
const {count, setCount} = useState(0);
const dispatch = useDispatch();
const handleIncrementClick= useCallback(
(e: MouseEvent) => {
setCcount(count + 1);
dispatch(counterActions.increment({ add: 1 }));
},
[count, dispatch]
);
const handleResetClick= useCallback(
(e: MouseEvent) => {
setCcount(0);
},
[count]
);
return [count, handleIncrementClick, handleResetClick];
};
以這種方式實現時,以下哪個是更好的 UnitTest?
1:只為實現為CustomHooks的useCounter
函數編寫單獨的測試,並為Counter
組件本身編寫一個測試。 (例如, useCounter.test.ts
/ counter.test.tsx
)
2:只測試使用useCounter
的Counter
組件(不要為useCounter
本身編寫UnitTest)
我更喜歡選項二,使用react-testing-library
僅測試Counter
組件的行為。 使用鈎子是一個實現細節,在“集成”測試中測試組件的行為是這種情況下的方法。 以這種方式進行測試還將反映最終用戶將使用您的組件的方式。
但是,如果您要創建要發布以供其他開發人員重用的掛鈎,則情況會發生變化。 在這種情況下,鈎子將成為您的包 API 的一部分,因此應單獨對其進行測試。
我還必須說,這是個人喜好的問題,有些人更喜歡對所有內容進行單元測試。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.