Skip to content
Advertisement

How to test if a component is rendered with the right props when using react-testing-library?

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.

Advertisement

Answer

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)
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement