iT邦幫忙

2021 iThome 鐵人賽

DAY 21
0
Modern Web

用Jest和Enzyme來寫React測試吧!!系列 第 21

【Day21】補上data-test屬性及判斷Component和按鈕及數字是否正確顯示(╯✧∇✧)╯

基本上我們會用到 計數器這整個Component (div) 、顯示數字 (span)、按鈕(button)這三個DOM,

所以先在我們的Component上加上data-test屬性吧!


  • Div Dom
 <Container className="App" data-test="component-app">
 
 </Container>
  • Span Dom

     <h1 data-test="counter-display">
        <FontAwesomeIcon icon={faHeart} style={{color:"red"}}/>&nbsp;&nbsp;
        <span data-test="count">{count}</span>
    </h1>
    
  • Button Dom

    <Button variant="primary"
                        data-test="increment-button"
                        size="lg"
                        onClick={() => setCount(count + 1)}
                    >
                        Give me a heart !
    </Button>
    

加完屬性後,先來第一個單元測試 => Component是否正確顯示

test('renders without errors', () => {
  const wrapper= setup();

  const appComponent=findByTestAttribute(wrapper,"component-app");
  expect(appComponent.length).toBe(1);

});

還記得setup這個function哪來的嗎? 前面我們有將重複會用到的code寫成共用function,

setup這個function就是拿來渲染我們的Component,渲染完後,
我們要用data-test屬性一樣透過先前寫的共用function =>findByTestAttribute 來找Component,
我們期望找到的是「1個」Component。

到這邊先執行npm test 看一下有沒有錯誤吧~ ( YA~~ PASS了!


接下來用一樣的方式來看看按鈕跟數字是否正確顯示吧!

  • Button

    test("render button",()=>{
      const wrapper= setup();
    
      const incrementButtont=findByTestAttribute(wrapper,"increment-button");
      expect(incrementButtont.length).toBe(1);
    });
    
  • Span

    test("counter display",()=>{
    
      const wrapper= setup();
      const counterDisplay=findByTestAttribute(wrapper,"count");
      expect(counterDisplay.length).toBe(1);
    });
    

寫完以後,按存檔其實測試就會自己Reload囉! ( YA~~又Pass了!

還有測試計數器數值的初始值和按按鈕的單元測試還沒寫,下一篇來把它補齊吧!

快了!我們快要完成第一個Component的測試了

加油啊!!! 測試完成了的話,小菜鳥會再做一些關於React的補充和自己踩過的一些小地雷(๑•̀ㅂ•́)و✧


上一篇
【Day20】建立計數器的Test,並提供測試使用的方法 ୧☉□☉୨!
下一篇
【Day22】判斷計數器數字初始值是否為0且按下增加的按鈕時結果是否正確 「(°ヘ°)
系列文
用Jest和Enzyme來寫React測試吧!!30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言