score:51

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

score:0

In my case, I wanted to test that a Higher Order Component (HOC), correctly enhances the component that is passed to the HOC.

What I needed to do, is make the actual component a mock and pass it to the HOC. Like described in the existing answer, you can then just expect the properties, added by the HOC.

// after 'Component' get's passed into withSelectionConstraint, it should have an id prop
const Component = jest.fn(() => <h1>Tag Zam</h1>);
const WithConstraint = withSelectionConstraint(Component, ["instance"], true);
render(<WithConstraint />);

// passing the jest mock to the HOC, enables asserting the actual properties passed by the HOC
expect(Component).toHaveBeenCalledWith(
    expect.objectContaining({ ids: mockInstanceRows.map(x => x.id) }), 
    expect.anything()
)


score:7

Don't believe it's possible. RTL looks like focusing on validating against DOM not React's components tree.

The only workaround I see is to mock FetchNextPageButton to make it rendering all props into attributes.

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

Sure, this is smoothly only for primitive values in props, but validating something like object or function would be harder.

Think, it's not RTL-way, but I agree it would be massive work to check that in scope of each container(and completely ignoring that would be rather a risk).

PS toHaveAttribute is from jest-dom


Related Query

More Query from same tag