iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 27
3
Modern Web

TypeScript + React + 雜七雜八系列 第 27

【Day 27】React Testing Library

  • 分享至 

  • xImage
  •  

大家好,今天的篇章要介紹 React Testing Library

會延續前一天的專案結構接續下去進行修改,如果沒有參與到昨天的建置過程,這邊也有提供原始碼
https://github.com/littlehorseboy/typescript-react/tree/day26-jest


React Testing Library

React Testing Library 是用於測試 React 組件的非常輕巧的解決方案

The more your tests resemble the way your software is used, the more confidence they can give you.

您的測試將與實際的 DOM 節點一起使用,而不是處理渲染的 React 組件的實例。該庫提供的實用程序可以方便地以與用戶查詢方式相同的方式查詢 DOM。通過標籤文本查找元素(就像用戶看到的一樣),從文本中找到鏈接和按鈕(就像用戶看到的一樣)。它還公開了一種建議的方法,data-testid 的方式查找那些內容和標籤不合理或不實際的元素

直接安裝起來然後隨便找一個不要太複雜的 tsx 來玩看看

npm i -D @testing-library/react
npm i -D @testing-library/jest-dom

DraftJsPractice.tsx 增加 data-testid="draftjs-editor"

+ src/components/DraftJsPractice/DraftJsPractice.test.tsx

執行結果

npm run test -- src/components/DraftJsPractice/DraftJsPractice.test.tsx

測試結果 editor 在 change 前後的值都符合 expect 條件


以上就是用 React Testing Library 寫測試程式碼的小小範例

最後附上原始碼
https://github.com/littlehorseboy/typescript-react/tree/day27-react-testing-library


明天還會繼續寫 React Testing Library,用專案內的 tsx 來寫各種測試程式碼


上一篇
【Day 26】Jest,Mock
下一篇
【Day 28】React Testing Library
系列文
TypeScript + React + 雜七雜八30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言