Skip to content

Commit b8d0042

Browse files
kdquistanchalalopenchi
authored andcommitted
toContainElement() assertion
1 parent d93e39c commit b8d0042

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
@@ -148,6 +148,50 @@ export class ElementAssertion extends Assertion<ReactTestInstance> {
148148
});
149149
}
150150

151+
/**
152+
* Check if an element is contained within another element.
153+
*
154+
* @example
155+
* ```
156+
* expect(parent).toContainElement(child);
157+
* ```
158+
*
159+
* @param element - The element to check for.
160+
* @returns the assertion instance
161+
*/
162+
public toContainElement(element: ReactTestInstance): this {
163+
const error = new AssertionError({
164+
actual: this.actual,
165+
message: `Expected element ${this.toString()} to contain element ${instanceToString(element)}.`,
166+
});
167+
const invertedError = new AssertionError({
168+
actual: this.actual,
169+
message: `Expected element ${this.toString()} NOT to contain element ${instanceToString(element)}.`,
170+
});
171+
172+
const isElementContained = (
173+
parentElement: ReactTestInstance,
174+
childElement: ReactTestInstance,
175+
): boolean => {
176+
if (parentElement === null || childElement === null) {
177+
return false;
178+
}
179+
180+
return (
181+
parentElement.findAll(
182+
node =>
183+
node.type === childElement.type && node.props === childElement.props,
184+
).length > 0
185+
);
186+
};
187+
188+
return this.execute({
189+
assertWhen: isElementContained(this.actual, element),
190+
error,
191+
invertedError,
192+
});
193+
}
194+
151195
private isElementDisabled(element: ReactTestInstance): boolean {
152196
const { type } = element;
153197
const elementType = type.toString();

0 commit comments

Comments
 (0)