From 4fed5aeab5334e871c71bd53e2da61907119d0f3 Mon Sep 17 00:00:00 2001 From: "Kent C. Dodds" Date: Fri, 13 Dec 2019 08:26:43 -0700 Subject: [PATCH] feat(screen): Add screen export which has all queries bound to the body (#412) --- src/__node_tests__/screen.js | 9 +++++++++ src/__tests__/screen.js | 9 +++++++++ src/index.js | 1 + src/screen.js | 14 ++++++++++++++ 4 files changed, 33 insertions(+) create mode 100644 src/__node_tests__/screen.js create mode 100644 src/__tests__/screen.js create mode 100644 src/screen.js diff --git a/src/__node_tests__/screen.js b/src/__node_tests__/screen.js new file mode 100644 index 00000000..896393d0 --- /dev/null +++ b/src/__node_tests__/screen.js @@ -0,0 +1,9 @@ +import {screen} from '..' + +test('the screen export throws a helpful error message when no global document is accessible', () => { + expect(() => + screen.getByText(/hello world/i), + ).toThrowErrorMatchingInlineSnapshot( + `"For queries bound to document.body a global document has to be available... Learn more: https://testing-library.com/s/screen-global-error"`, + ) +}) diff --git a/src/__tests__/screen.js b/src/__tests__/screen.js new file mode 100644 index 00000000..b1dc5c7c --- /dev/null +++ b/src/__tests__/screen.js @@ -0,0 +1,9 @@ +import {renderIntoDocument} from './helpers/test-utils' +import {screen} from '..' + +test('exposes queries that are attached to document.body', async () => { + renderIntoDocument(`
hello world
`) + screen.getByText(/hello world/i) + await screen.findByText(/hello world/i) + expect(screen.queryByText(/hello world/i)).not.toBeNull() +}) diff --git a/src/index.js b/src/index.js index 1469303f..2cfa048f 100644 --- a/src/index.js +++ b/src/index.js @@ -11,6 +11,7 @@ export {getDefaultNormalizer} from './matches' export * from './get-node-text' export * from './events' export * from './get-queries-for-element' +export * from './screen' export * from './query-helpers' export {getRoles, logRoles, isInaccessible} from './role-helpers' export * from './pretty-dom' diff --git a/src/screen.js b/src/screen.js new file mode 100644 index 00000000..51b25416 --- /dev/null +++ b/src/screen.js @@ -0,0 +1,14 @@ +import * as queries from './queries' +import {getQueriesForElement} from './get-queries-for-element' + +export const screen = + typeof document !== 'undefined' && document.body + ? getQueriesForElement(document.body) + : Object.keys(queries).reduce((helpers, key) => { + helpers[key] = () => { + throw new TypeError( + 'For queries bound to document.body a global document has to be available... Learn more: https://testing-library.com/s/screen-global-error', + ) + } + return helpers + }, {})