Javascript 如何在使用react测试库时测试组件是否使用正确的道具呈现?

Javascript 如何在使用react测试库时测试组件是否使用正确的道具呈现?,javascript,reactjs,jestjs,react-testing-library,Javascript,Reactjs,Jestjs,React Testing Library,我有一些组件正在呈现另一个已经单独测试的组件(FetchNextPageButton),例如: const News = () => ( <div> <h1>News</h1> ... <FetchNextPageButton query={NEWS_QUERY} path="viewer.news" /> </div> ) const Jobs = () => ( <div>

我有一些组件正在呈现另一个已经单独测试的组件(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>
)

所以我想知道用什么样的方法来测试它最好。

不要相信这是可能的。RTL似乎专注于根据DOM的组件树进行验证

我看到的唯一解决方法是模拟
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");
jest.mock(“../../../FetchNextPageButton.js”,()=>
(道具)=>);
....
const{getByTestId}=render();
expect(getByTestId(“FetchNextPageButton”).toHaveAttribute(“查询”,新闻查询);
expect(getByTestId(“FetchNextPageButton”).toHaveAttribute(“path”、“viewer.news”);
当然,这只适用于道具中的基本值,但验证对象或函数之类的东西会更困难

想一想,这不是RTL方式,但我同意在每个容器的范围内检查它将是一项巨大的工作(完全忽略这将是一个相当大的风险)


PS
toHaveAttribute
来自

这是Kent C.Dodds(RTL的创建者)与我讨论后分享的方法:

import FetchNextPageButton from 'FetchNextPageButton'

jest.mock('FetchNextPageButton', () => {
  return jest.fn(() => null)
})

// ... in your test
expect(FetchNextPageButton).toHaveBeenCalledWith(props, context)

@亚历克斯麦凯:我们在推特上讨论过:我是唯一一个不合作的人吗?当我运行它时,它声明:Matcher error:received value必须是mock或spy function received has type:function received has value:[函数组件]@Youans您必须先模拟组件,然后将其传递给断言。注意:Kent C.Dodds不推荐这种方法。他写了一段代码,展示了如何做到这一点,但他说他不推荐这种方法(这也在twitter线程中)。类似的问题@Doug我理解他不建议按经验做这件事,但如果你不得不这么做(他说,可能有很好的理由单独测试),他实际上就是这样做的。
import FetchNextPageButton from 'FetchNextPageButton'

jest.mock('FetchNextPageButton', () => {
  return jest.fn(() => null)
})

// ... in your test
expect(FetchNextPageButton).toHaveBeenCalledWith(props, context)