簡體   English   中英

React -Jest 調用 UseEffect

[英]React -Jest Invoke UseEffect

我在更改狀態的代碼中有依賴性 useeffect -

 useEffect(()=>{
     if(open)
      {
        setOpen(false);
      }    
    },[open]); //open is a state variable which changes with setOpen(true/false);

我的代碼覆蓋率為此顯示紅線。 我怎樣才能用玩笑來測試這個? (由於某些項目原因,我不能使用酶,決定權不在我手中)

我試過了 -

beforeAll(()=>{
    useState.mockImplementation(callback=>{
       return callback({
            open:true
         })
    }) 
});

test("Check State",async ()=>{
  render(<ControlToRender/>);
  await act(()=> expect(open).toBe(false);
})

當我這樣做時出現錯誤 - npm 運行測試 -

useState.mockImplementation is not a function

我相信您應該將組件作為 balckbox 進行測試,而不是 useState 內部實現本身。 類似於 - 用戶操作 - 預期行為(元素是否可見)。 mocking global useState 的做法是不可持續的。 如果另一個開發人員在組件中添加另一個 useState 怎么辦?

更多行為驅動示例:

test("Given XXX the alert should be visible",async ()=>{
  render(<ControlToRender/>);
  await act(()=> {
    const errorMessageNode = screen.getByRole("alert");
    expect(errorMessageNode).toBeVisible();
  });
})

暫無
暫無

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

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