使用 react-testing-library 时如何测试组件是否使用正确的道具呈现? [英] How to test if a component is rendered with the right props when using react-testing-library?

查看:68
本文介绍了使用 react-testing-library 时如何测试组件是否使用正确的道具呈现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些组件正在渲染另一个已经单独测试过的组件 (FetchNextPageButton),例如:

const News = () =>(<div><h1>新闻</h1>...<FetchNextPageButton query={NEWS_QUERY} path="viewer.news"/>

)const 乔布斯 = () =>(<div><h1>工作</h1>...<FetchNextPageButton query={JOBS_QUERY} path="viewer.jobs"/>

)const 帖子 = () =>(<div><h1>帖子</h1>...<FetchNextPageButton query={POSTS_QUERY} path="viewer.posts"/>

)

问题是我不想为已经在其他地方测试过的功能添加对这些组件中的每一个的测试,所以我认为这应该足以测试组件是否已呈现并且我'我将正确的道具传递给它.

我本来可以使用 Enzyme 轻松地进行测试,如下所示:

expect(wrapper.find('FetchNextPageButton').props()).toMatchObject({查询:NEWS_QUERY,路径:viewer.news"})

所以我想知道使用 React 测试库进行测试的最佳方法是什么 代替.

解决方案

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

从'FetchNextPageButton'导入FetchNextPageButtonjest.mock('FetchNextPageButton', () => {返回 jest.fn(() => null)})//... 在你的测试中期望(FetchNextPageButton).toHaveBeenCalledWith(道具,上下文)

I have some components that are rendering another component (FetchNextPageButton) that is already tested in isolation, like these ones:

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>
)

The thing is that I'd not like having to add tests on each of these components for a functionality that is already tested somewhere else, so I think that should be enough just to test that the component is rendered and that I'm passing the right props to it.

I'd have been able to test this easily with Enzyme with something like this:

expect(wrapper.find('FetchNextPageButton').props()).toMatchObject({
  query: NEWS_QUERY,
  path: "viewer.news"
})

So I'm wondering what's the best approach to test it by using React testing library instead.

解决方案

This is the approach that Kent C. Dodds (the creator of RTL) shared with me after discussing it with him:

import FetchNextPageButton from 'FetchNextPageButton'

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

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

这篇关于使用 react-testing-library 时如何测试组件是否使用正确的道具呈现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆