[英]How to test react component with onClick function Jest/React testing library
[英]How to render a conditional component in a Test file? React Testing Library
我有一個 React 組件,它在fetchUser
status is not loading
之前不會呈現。 我的測試失敗,因為該組件沒有第一次呈現,因此找不到page loaded
文本。 如何在我的測試中模擬我的const [fetchStatusLoading, setFetchStatusLoading] = useState(false)
以便呈現頁面而不是loading
文本?
const fetchUser = useSelector((state) => (state.fetchUser));
const [fetchStatusLoading, setFetchStatusLoading] = useState(true);
useEffect(() => {
setFetchStatusLoading(fetchUser .status === 'loading');
}, [fetchStatusLoading, fetch.status]);
useEffect(() => {
// this is a redux thunk dispatch that sets fetch.status to loading/succeeded
dispatch(fetchAPI({ username }));
}, []);
if(fetchStatusLoading) return 'loading..';
return (<>page loaded</>)
// test case fails
expect(getByText('page loaded')).toBeInTheDocument();
如果您能夠模擬加載 state 您將只測試“渲染”部分上的代碼,而不是您應該測試的所有組件邏輯,因為這是測試庫意味着發光的方式。
如果這只是一個異步問題,您可以執行以下操作:
test('test page loaded', async () => {
render(<MyComponent />);
expect(await screen.findByText('page loaded')).toBeInTheDocument();
});
但是您的組件似乎包含一個 API 請求,因此如果該組件接受 function 您可以模擬它並返回值,或者您可以模擬提取。 以下是您不應該這樣做的一些原因。
使用nock
或mock-service-worker
您可以擁有一個假服務器來響應您的 API 請求,因此無需模擬任何內部 state 即可運行您的組件測試。
測試庫只是在類似瀏覽器的環境中呈現組件,並且不提供 API 來修改任何道具或 state。 它是為此目的而創建的,與 Enzyme 相反,它提供了一個 API 來訪問組件 props 和 state。
查看這個類似的問題: 使用反應測試庫檢查組件的 state
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.