Skip to content

Commit 4fed5ae

Browse files
author
Kent C. Dodds
authored
feat(screen): Add screen export which has all queries bound to the body (testing-library#412)
1 parent 60b65f5 commit 4fed5ae

File tree

4 files changed

+33
-0
lines changed

4 files changed

+33
-0
lines changed

src/__node_tests__/screen.js

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
import {screen} from '..'
2+
3+
test('the screen export throws a helpful error message when no global document is accessible', () => {
4+
expect(() =>
5+
screen.getByText(/hello world/i),
6+
).toThrowErrorMatchingInlineSnapshot(
7+
`"For queries bound to document.body a global document has to be available... Learn more: https://testing-library.com/s/screen-global-error"`,
8+
)
9+
})

src/__tests__/screen.js

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
import {renderIntoDocument} from './helpers/test-utils'
2+
import {screen} from '..'
3+
4+
test('exposes queries that are attached to document.body', async () => {
5+
renderIntoDocument(`<div>hello world</div>`)
6+
screen.getByText(/hello world/i)
7+
await screen.findByText(/hello world/i)
8+
expect(screen.queryByText(/hello world/i)).not.toBeNull()
9+
})

src/index.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ export {getDefaultNormalizer} from './matches'
1111
export * from './get-node-text'
1212
export * from './events'
1313
export * from './get-queries-for-element'
14+
export * from './screen'
1415
export * from './query-helpers'
1516
export {getRoles, logRoles, isInaccessible} from './role-helpers'
1617
export * from './pretty-dom'

src/screen.js

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import * as queries from './queries'
2+
import {getQueriesForElement} from './get-queries-for-element'
3+
4+
export const screen =
5+
typeof document !== 'undefined' && document.body
6+
? getQueriesForElement(document.body)
7+
: Object.keys(queries).reduce((helpers, key) => {
8+
helpers[key] = () => {
9+
throw new TypeError(
10+
'For queries bound to document.body a global document has to be available... Learn more: https://testing-library.com/s/screen-global-error',
11+
)
12+
}
13+
return helpers
14+
}, {})

0 commit comments

Comments
 (0)