Skip to content

Commit

Permalink
Make screen compatible with document.body.replaceWith()
Browse files Browse the repository at this point in the history
What:

The screen utility no longer caches the body element at import time.
When the body or entire HTML document changes with replaceWith(), the
screen utility continues to operate on the global value.

Why:

My integration testing environment strives to creates testing scenarios
that are as realistic to production as possible. This aligns with the
library's guiding principles:

> We try to only expose methods and utilities that encourage you to
> write tests that closely resemble how your web pages are used.

To assist with this, parts of my integration testing environment involve
a 2-step process:

1. Run a command to dump the HTML documents rendered by the backend.
2. Load those dumps into a Jest test environment to assert JavaScript
behavior.

Loading the HTML document in Jest is a challenge as the global HTML
document is setup by jest-environment-jsdom ahead of the test running.
To make this work well, the environment "replaces" the jsdom HTML
document like:

```
const content = loadHTML(...);
const tmpDom = new jsdom.JSDOM(content);
const tmpDocument = tmpDom.window.document;
// Replace the global document with the one from the backend.
document.documentElement.replaceWith(document.adoptNode(tmpDocument.documentElement));
```

This works out great in practice for me. The JavaScript is tested
against real HTML documents rather than fabricated ones for the test. In
the event that the backend changes how elements are rendered that, the
integration tests will expose this and force a fix to make the two
compatible.

With this change, the screen utility is now usable as a convenience.

How:

Rather than caching the document.body at import time, screen now
dynamically uses the most up date value on the global document.
  • Loading branch information
jdufresne committed Apr 28, 2024
1 parent 7917358 commit 430e952
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 16 deletions.
9 changes: 9 additions & 0 deletions src/__tests__/screen.js
Original file line number Diff line number Diff line change
Expand Up @@ -118,3 +118,12 @@ test('exposes debug method', () => {
`)
console.log.mockClear()
})

test('queries after replaceWith', async () => {
const newBody = document.createElement('body')
newBody.innerHTML = '<div>replaceWith element</div>'
document.body.replaceWith(newBody)
screen.getByText('replaceWith element')
await screen.findByText('replaceWith element')
expect(screen.queryByText('replaceWith element')).not.toBeNull()
})
32 changes: 16 additions & 16 deletions src/screen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
// TODO: Statically verify we don't rely on NodeJS implicit named imports.
import lzString from 'lz-string'
import {type OptionsReceived} from 'pretty-format'
import {getQueriesForElement} from './get-queries-for-element'
import {getDocument} from './helpers'
import {logDOM} from './pretty-dom'
import * as queries from './queries'
Expand Down Expand Up @@ -46,19 +45,20 @@ const logTestingPlaygroundURL = (element = getDocument().body) => {
return playgroundUrl
}

const initialValue = {debug, logTestingPlaygroundURL}
const initialValue: Record<string, Function> = {debug, logTestingPlaygroundURL}

export const screen =
typeof document !== 'undefined' && document.body // eslint-disable-line @typescript-eslint/no-unnecessary-condition
? getQueriesForElement(document.body, queries, initialValue)
: Object.keys(queries).reduce((helpers, key) => {
// `key` is for all intents and purposes the type of keyof `helpers`, which itself is the type of `initialValue` plus incoming properties from `queries`
// if `Object.keys(something)` returned Array<keyof typeof something> this explicit type assertion would not be necessary
// see https://stackoverflow.com/questions/55012174/why-doesnt-object-keys-return-a-keyof-type-in-typescript
helpers[key as keyof typeof initialValue] = () => {
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
}, initialValue)
export const screen = Object.entries(queries).reduce((helpers, [key, fn]) => {
// `key` is for all intents and purposes the type of keyof `helpers`, which itself is the type of `initialValue` plus incoming properties from `queries`
// if `Object.keys(something)` returned Array<keyof typeof something> this explicit type assertion would not be necessary
// see https://stackoverflow.com/questions/55012174/why-doesnt-object-keys-return-a-keyof-type-in-typescript
helpers[key] = (...args: any[]) => {
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (typeof document === 'undefined' || !document.body) {
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 fn(document.body, ...(args as any[]))
}
return helpers
}, initialValue)

0 comments on commit 430e952

Please sign in to comment.