Skip to content
This repository was archived by the owner on Jan 10, 2025. It is now read-only.
This repository was archived by the owner on Jan 10, 2025. It is now read-only.

[@shopify/react-testing] Extend "toHaveReactComponent" matcher to search props #2286

Open
@markmur

Description

@markmur

Type

  • New feature
  • Changes to existing features

Overview

Hey folks, on a couple of occasions recently I've found myself trying to use the toContainReactComponent matcher to test for the presence of an underlying component in another component, but specified as a prop, rather than a child.

As I understand it, the underlying find function (shown below) only checks for the presence of the component in descendants and not props.

export function toContainReactComponent<
Type extends string | ComponentType<any>
>(
this: jest.MatcherUtils,
node: Node<unknown>,
type: Type,
props?: Partial<PropsFor<Type>>,
) {
assertIsNode(node, {
expectation: 'toContainReactComponent',
isNot: this.isNot,
});
assertIsType(type, {
expectation: 'toContainReactComponent',
isNot: this.isNot,
});
const foundByType = node.findAll(type);

Motivation

We're building a component for an internal project that allows consumers to specify a prop as either a string or ReactNode:

<SomeComponent
   summary={<Summary />}
>
  Some child content
</SomeComponent>

I would expect that the following jest matcher would find the component in the rendered tree, regardless of whether it's specified as a prop or a child:

expect(rendered.find(SomeComponent)).toContainReactComponent(Summary)

Is the implementation intentionally built to only check descendants? or would the team be open to adding support for props?

If the latter, I would be happy to provide a PR for this. My intention would be to update the toContainReactComponent function to include props OR create a new custom matcher - depending on the teams preferences.

Area

Testing

Scope

@shopify/react-testing


Checklist

  • Please delete the labels section before submitting your issue
  • I have described this issue in a way that is actionable (if possible)

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions