Skip to content

Commit 0c30fee

Browse files
toContainElement() assertion
1 parent abf480a commit 0c30fee

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

packages/native/src/lib/ElementAssertion.ts

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,50 @@ export class ElementAssertion extends Assertion<ReactTestInstance> {
120120
});
121121
}
122122

123+
/**
124+
* Check if an element is contained within another element.
125+
*
126+
* @example
127+
* ```
128+
* expect(parent).toContainElement(child);
129+
* ```
130+
*
131+
* @param element - The element to check for.
132+
* @returns the assertion instance
133+
*/
134+
public toContainElement(element: ReactTestInstance): this {
135+
const error = new AssertionError({
136+
actual: this.actual,
137+
message: `Expected element ${this.toString()} to contain element ${instanceToString(element)}.`,
138+
});
139+
const invertedError = new AssertionError({
140+
actual: this.actual,
141+
message: `Expected element ${this.toString()} NOT to contain element ${instanceToString(element)}.`,
142+
});
143+
144+
const isElementContained = (
145+
parentElement: ReactTestInstance,
146+
childElement: ReactTestInstance,
147+
): boolean => {
148+
if (parentElement === null || childElement === null) {
149+
return false;
150+
}
151+
152+
return (
153+
parentElement.findAll(
154+
node =>
155+
node.type === childElement.type && node.props === childElement.props,
156+
).length > 0
157+
);
158+
};
159+
160+
return this.execute({
161+
assertWhen: isElementContained(this.actual, element),
162+
error,
163+
invertedError,
164+
});
165+
}
166+
123167
private isElementDisabled(element: ReactTestInstance): boolean {
124168
const { type } = element;
125169
const elementType = type.toString();

0 commit comments

Comments
 (0)