![](/img/trans.png)
[英]Test a react component using test and react-testing-library
[英]How to test if a component is rendered with the right props when using react-testing-library?
我有一些組件正在渲染另一個已經單獨測試過的組件(FetchNextPageButton),比如這些:
const News = () => (
<div>
<h1>News</h1>
...
<FetchNextPageButton query={NEWS_QUERY} path="viewer.news" />
</div>
)
const Jobs = () => (
<div>
<h1>Jobs</h1>
...
<FetchNextPageButton query={JOBS_QUERY} path="viewer.jobs" />
</div>
)
const Posts = () => (
<div>
<h1>Posts</h1>
...
<FetchNextPageButton query={POSTS_QUERY} path="viewer.posts" />
</div>
)
問題是我不希望為已經在其他地方測試過的功能在每個組件上添加測試,所以我認為這足以測試組件是否已呈現並且我正在通過正確的道具。
我已經能夠使用 Enzyme 輕松地進行測試,如下所示:
expect(wrapper.find('FetchNextPageButton').props()).toMatchObject({
query: NEWS_QUERY,
path: "viewer.news"
})
所以我想知道通過使用React 測試庫來測試它的最佳方法是什么。
這就是 Kent C 的方法。 Dodds(RTL 的創造者)與他討論后與我分享:
import FetchNextPageButton from 'FetchNextPageButton'
jest.mock('FetchNextPageButton', () => {
return jest.fn(() => null)
})
// ... in your test
expect(FetchNextPageButton).toHaveBeenCalledWith(props, context)
不要相信這是可能的。 RTL 看起來專注於驗證 DOM 而不是 React 的組件樹。
我看到的唯一解決方法是模擬FetchNextPageButton
以使其將所有道具渲染為屬性。
jest.mock("../../../FetchNextPageButton.js", () =>
(props) => <div data-test-id="FetchNextPageButton" {...props} />);
....
const { getByTestId } = render(<YourComponent />);
expect(getByTestId("FetchNextPageButton")).toHaveAttribute("query", NEWS_QUERY);
expect(getByTestId("FetchNextPageButton")).toHaveAttribute("path", "viewer.news");
當然,這僅適用於 props 中的原始值,但驗證 object 或 function 之類的東西會更難。
想想,這不是 RTL 方式,但我同意在每個容器的 scope 中檢查它將是一項巨大的工作(並且完全忽略這將是相當冒險的)。
PS toHaveAttribute
來自jest-dom
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.