簡體   English   中英

使用 Jest + react-testing-library 測試異步 `componentDidMount()`

[英]Testing async `componentDidMount()` with Jest + react-testing-library

我有一個在componentDidMount()中異步獲取數據的組件

componentDidMount() {
  const self = this;

  const url = "/some/path";
  const data = {}
  const config = {
    headers: { "Content-Type": "application/json", "Accept": "application/json" }
  };

  axios.get(url, data, config)
    .then(function(response) {
      // Do success stuff

      self.setState({ .... });
    })
    .catch(function(error) {
      // Do failure stuff

      self.setState({ .... });
    })
  ;
}

我對該組件的測試如下所示 -

it("renders the component correctly", async () => {
  // Have API return some random data;
  let data = { some: { random: ["data to be returned"] } };
  axios.get.mockResolvedValue({ data: data });

  const rendered = render(<MyComponent />);
  // Not sure what I should be awaiting here
  await ???

  // Test that certain elements render
  const toggleContainer = rendered.getByTestId("some-test-id");
  expect(toggleContainer).not.toBeNull();
});

由於渲染和加載數據是異步的,我的expect()語句 go 提前執行並在componentDidMount()和偽異步調用完成執行之前執行,因此expect()語句總是失敗。

我想我可以引入某種延遲,但感覺不對,當然會增加我的測試運行時間。

這個類似的問題這個要點片段都展示了我如何用酶來測試它。 本質上,他們依靠async / await手動調用componentDidMount()

然而react-testing-library似乎不允許直接訪問組件以直接調用其方法(可能是設計使然)。 所以我不確定要等待“什么”,或者這是否是正確的方法。

謝謝!

這取決於您的組件在做什么。 想象一下,您的組件顯示一條加載消息,然后顯示一條歡迎消息。 您將等待歡迎消息出現:

const { getByText, findByText } = render(<MyComponent />)
expect(getByText('Loading...')).toBeInTheDocument()
expect(await findByText('Welcome back!')).toBeInTheDocument()

考慮它的最佳方法是打開瀏覽器查看您的組件。 什么時候知道它被加載了? 嘗試在您的測試中重現它。

您需要用act包裝render以解決警告消息causes React state updates should be wrapped into act中。

例如:

it("renders the component correctly", async () => {
  // Have API return some random data;
  let data = { some: { random: ["data to be returned"] } };
  axios.get.mockResolvedValue({ data: data });

  const rendered = await act(() => render(<MyComponent />));

  // Test that certain elements render
  const toggleContainer = rendered.getByTestId("some-test-id");
  expect(toggleContainer).not.toBeNull();
});

反應測試庫也是如此。

暫無
暫無

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

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