Stabilise React useId values in DOM snapshots in element-web (#33579)
* Stabilise React useId values in DOM snapshots - app/web * Stabilise React useId values in DOM snapshots - shared components * Update additional snapshots * Added comments and changed replace pattern to 'react-use-id-N'
This commit is contained in:
@@ -22,6 +22,43 @@ declare global {
|
||||
|
||||
globalThis.IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
const REACT_USE_ID = /_r_[a-z0-9]+_/g;
|
||||
|
||||
function normaliseReactUseIds(snapshot: string): string {
|
||||
// React useId values can vary between runs and make snapshots flaky:
|
||||
// https://github.com/element-hq/element-web/issues/31765
|
||||
// Avoid running the regex for DOM snapshots without React useId output.
|
||||
if (!snapshot.includes("_r_")) return snapshot;
|
||||
|
||||
const ids = new Map<string, string>();
|
||||
let nextId = 1;
|
||||
|
||||
return snapshot.replace(REACT_USE_ID, (id) => {
|
||||
let replacement = ids.get(id);
|
||||
if (!replacement) {
|
||||
replacement = `react-use-id-${nextId++}`;
|
||||
ids.set(id, replacement);
|
||||
}
|
||||
return replacement;
|
||||
});
|
||||
}
|
||||
|
||||
// Prevent this serializer from recursively matching the same DOM node when it calls serialize().
|
||||
let isSerializingDomSnapshot = false;
|
||||
|
||||
expect.addSnapshotSerializer({
|
||||
test: (value: unknown): value is Element | DocumentFragment =>
|
||||
!isSerializingDomSnapshot && (value instanceof Element || value instanceof DocumentFragment),
|
||||
print: (value: unknown, serialize: (value: unknown) => string): string => {
|
||||
isSerializingDomSnapshot = true;
|
||||
try {
|
||||
return normaliseReactUseIds(serialize(value));
|
||||
} finally {
|
||||
isSerializingDomSnapshot = false;
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
// Fake random strings to give a predictable snapshot for IDs
|
||||
jest.mock("matrix-js-sdk/src/randomstring");
|
||||
beforeEach(() => {
|
||||
|
||||
Reference in New Issue
Block a user