From 430e9528b0ebbe5d5417dc794f6f81547f0f84e9 Mon Sep 17 00:00:00 2001 From: Jon Dufresne Date: Sat, 27 Apr 2024 18:53:11 -0700 Subject: [PATCH] Make screen compatible with document.body.replaceWith() 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. --- src/__tests__/screen.js | 9 +++++++++ src/screen.ts | 32 ++++++++++++++++---------------- 2 files changed, 25 insertions(+), 16 deletions(-) diff --git a/src/__tests__/screen.js b/src/__tests__/screen.js index 7c57de4a..7c188357 100644 --- a/src/__tests__/screen.js +++ b/src/__tests__/screen.js @@ -118,3 +118,12 @@ test('exposes debug method', () => { `) console.log.mockClear() }) + +test('queries after replaceWith', async () => { + const newBody = document.createElement('body') + newBody.innerHTML = '
replaceWith element
' + document.body.replaceWith(newBody) + screen.getByText('replaceWith element') + await screen.findByText('replaceWith element') + expect(screen.queryByText('replaceWith element')).not.toBeNull() +}) diff --git a/src/screen.ts b/src/screen.ts index fbe372ff..2cc691c9 100644 --- a/src/screen.ts +++ b/src/screen.ts @@ -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' @@ -46,19 +45,20 @@ const logTestingPlaygroundURL = (element = getDocument().body) => { return playgroundUrl } -const initialValue = {debug, logTestingPlaygroundURL} +const initialValue: Record = {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 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 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)