Skip to content

Commit a7b2c0b

Browse files
Add toBeVisible matcher
1 parent 8cbace8 commit a7b2c0b

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

packages/native/src/lib/ElementAssertion.ts

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,33 @@ export class ElementAssertion extends Assertion<ReactTestInstance> {
9494
});
9595
}
9696

97+
/**
98+
* Check if the element is visible.
99+
*
100+
* @example
101+
* ```
102+
* expect(element).toBeVisible();
103+
* ```
104+
*
105+
* @returns the assertion instance
106+
*/
107+
public toBeVisible(): this {
108+
const error = new AssertionError({
109+
actual: this.actual,
110+
message: `Expected element ${this.toString()} to be visible.`,
111+
});
112+
const invertedError = new AssertionError({
113+
actual: this.actual,
114+
message: `Expected element ${this.toString()} NOT to be visible.`,
115+
});
116+
117+
return this.execute({
118+
assertWhen: this.isElementVisible(this.actual) && !this.isAncestorNotVisible(this.actual),
119+
error,
120+
invertedError,
121+
});
122+
}
123+
97124
private isElementDisabled(element: ReactTestInstance): boolean {
98125
const { type } = element;
99126
const elementType = type.toString();
@@ -113,4 +140,24 @@ export class ElementAssertion extends Assertion<ReactTestInstance> {
113140
const { parent } = element;
114141
return parent !== null && (this.isElementDisabled(element) || this.isAncestorDisabled(parent));
115142
}
143+
144+
private isElementVisible(element: ReactTestInstance): boolean {
145+
const { type } = element;
146+
const elementType = type.toString();
147+
if (elementType === "Modal" && !element?.props?.visible === true) {
148+
return false;
149+
}
150+
151+
return (
152+
get(element, "props.style.display") !== "none"
153+
&& get(element, "props.style.opacity") !== 0
154+
&& get(element, "props.accessibilityElementsHidden") !== true
155+
&& get(element, "props.importantForAccessibility") !== "no-hide-descendants"
156+
);
157+
}
158+
159+
private isAncestorNotVisible(element: ReactTestInstance): boolean {
160+
const { parent } = element;
161+
return parent !== null && (!this.isElementVisible(element) || this.isAncestorNotVisible(parent));
162+
}
116163
}

0 commit comments

Comments
 (0)