Skip to content

Commit 4b13299

Browse files
authored
fix(devtools): (de)serialize query suggestions for msg transport (#233)
1 parent dc6bd70 commit 4b13299

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed

src/components/ResultQueries.js

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,33 @@ function Heading({ children }) {
1010
return <h3 className="text-xs font-bold">{children}</h3>;
1111
}
1212

13+
// The reviver parses serialized regexes back to a real regexp.
14+
// This function is required if the data comes in via message transport
15+
// think of the chrome-extension.
16+
function reviver(obj) {
17+
if (typeof obj?.$regexp === 'string') {
18+
return new RegExp(obj.$regexp, obj.$flags);
19+
}
20+
21+
return obj;
22+
}
23+
24+
// we use our own stringify method instead of the one from @testing-library/dom,
25+
// because it might have been removed for message transport.
26+
function suggestionToString({ queryArgs, queryMethod }) {
27+
let [text, options] = queryArgs;
28+
29+
text = typeof text === 'string' ? `'${text}'` : reviver(text);
30+
31+
options = options
32+
? `, { ${Object.entries(options)
33+
.map(([k, v]) => `${k}: ${reviver(v)}`)
34+
.join(', ')} }`
35+
: '';
36+
37+
return `${queryMethod}(${text}${options})`;
38+
}
39+
1340
const Field = React.memo(function Field({
1441
data,
1542
method,
@@ -19,11 +46,12 @@ const Field = React.memo(function Field({
1946
}) {
2047
const field = getFieldName(method);
2148
const value = data[field];
49+
2250
const handleClick = value
2351
? () => {
2452
dispatch({
2553
type: 'SET_QUERY',
26-
query: `screen.${query.toString()}`,
54+
query: `screen.${suggestionToString(query)}`,
2755
});
2856
}
2957
: undefined;

src/parser.js

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,11 @@ import {
1414

1515
import userEvent from '@testing-library/user-event';
1616

17+
// Patch RegeXP so we have a (better) way to serialize for message transport
18+
RegExp.prototype.toJSON = function () {
19+
return { $regexp: this.source, $flags: this.flags };
20+
};
21+
1722
const debug = (element, maxLength, options) =>
1823
Array.isArray(element)
1924
? element.map((el) => logDOM(el, maxLength, options)).join('\n')

0 commit comments

Comments
 (0)