簡體   English   中英

React 測試庫在反應片段中找不到我的自閉合標簽,而只是呈現<body/>

[英]React Testing Library can't find my self-closing tag in a react fragment, and just renders <body/>

我有一個這樣的組件:

const MyComponent = ({ foo }) => (
  <>
    <div>
    <Header />
      {foo}
    </div>
    <div data-testid="self-closing-tag" className={styles.break} />
  </>
)

(nb React 應該將 div 作為一個自閉合標簽來處理,而沒有 react 則不是有效的 html)

我編寫了一個測試,它為 foo 屬性呈現我的組件<div data-testid="foo" /> foo運行expect(screen.getByTestId('foo')).toBeInTheDocument(); 通過。 如果我在該測試中使用screen.debug ,我會得到完全渲染的 DOM。

但是當我為自閉標簽編寫測試時,如下所示: expect(screen.getByTestId('self-closing-tag')).toHaveClass('break'); 我得到:

無法通過以下方式獲取元素: [data-testid="self-closing-tag"]

在我希望它打印出完全渲染的 DOM 的地方,它只打印<body />

如果我將自閉合標簽的期望斷言放在“foo”的測試中,它們都通過了。

describe('<My Component />', () => {
  beforeEach(<MyComponent foo={<div data-testid="foo" />} />);
  it('renders foo', () => {
    expect(screen.getByTestId('foo')).toBeInTheDocument();
    // expect(screen.getByTestId('self-closing-tag')).toHaveClass('break'); -- this passes if uncommmented!
  };
  it('renders the self closing tag', () => {
    expect(screen.getByTestId('self-closing-tag')).toHaveClass('break'); // cannot find element, prints '<body />' as the DOM.
  })
})

我顯然可以將所有內容都放在同一個it語句中,但如果可能的話,我寧願不這樣做。 我也想了解是怎么回事。

我做錯了什么?

那是因為toHaveClass需要一個帶有類名的 arg,您可以在此處查看文檔。

因此,您的測試可能是:

expect(screen.getByTestId("self-closing-tag")).toHaveClass("XX class name you expect XX");

或者如果您只想檢查元素是否具有屬性類

expect(screen.getByTestId("self-closing-tag")).toHaveAttribute("class");

暫無
暫無

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

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