diff --git a/README.md b/README.md index 14e0c146..ed708d2e 100644 --- a/README.md +++ b/README.md @@ -420,6 +420,7 @@ This allows you to check if an element is currently visible to the user. An element is visible if **all** the following conditions are met: +- it is present in the document - it does not have its css property `display` set to `none` - it does not have its css property `visibility` set to either `hidden` or `collapse` diff --git a/src/__tests__/to-be-visible.js b/src/__tests__/to-be-visible.js index a715e2b9..f2b4277a 100644 --- a/src/__tests__/to-be-visible.js +++ b/src/__tests__/to-be-visible.js @@ -1,4 +1,5 @@ import {render} from './helpers/test-utils' +import document from './helpers/document' describe('.toBeVisible', () => { it('returns the visibility of an element', () => { @@ -35,6 +36,12 @@ describe('.toBeVisible', () => { ).toThrowError() }) + test('detached element is not visible', () => { + const subject = document.createElement('div') + expect(subject).not.toBeVisible() + expect(() => expect(subject).toBeVisible()).toThrowError() + }) + describe('with a
element', () => { let subject diff --git a/src/to-be-visible.js b/src/to-be-visible.js index 8837105e..518b7d56 100644 --- a/src/to-be-visible.js +++ b/src/to-be-visible.js @@ -32,7 +32,9 @@ function isElementVisible(element, previousElement) { export function toBeVisible(element) { checkHtmlElement(element, toBeVisible, this) - const isVisible = isElementVisible(element) + const isInDocument = + element.ownerDocument === element.getRootNode({composed: true}) + const isVisible = isInDocument && isElementVisible(element) return { pass: isVisible, message: () => { @@ -44,7 +46,9 @@ export function toBeVisible(element) { '', ), '', - `Received element ${is} visible:`, + `Received element ${is} visible${ + isInDocument ? '' : ' (element is not in the document)' + }:`, ` ${this.utils.printReceived(element.cloneNode(false))}`, ].join('\n') },