Skip to content

Commit b71962f

Browse files
committed
Extract a custom formatAsJSLiteral function
1 parent c5ce4ca commit b71962f

File tree

1 file changed

+11
-7
lines changed

1 file changed

+11
-7
lines changed

src/index.ts

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ export class Extension implements StringifyExtension {
3636
out.appendLine("")
3737

3838
// Test
39-
out.appendLine(`test(${JSON.stringify(flow.title)}, async () => {`)
39+
out.appendLine(`test(${formatAsJSLiteral(flow.title)}, async () => {`)
4040
out.startBlock()
4141
}
4242

@@ -52,7 +52,7 @@ export class Extension implements StringifyExtension {
5252
out.appendLine(
5353
`await userEvent.type(${stringifySelector(
5454
step.selectors[0],
55-
)}, ${JSON.stringify(step.value)})`,
55+
)}, ${formatAsJSLiteral(step.value)})`,
5656
)
5757
break
5858
case "click":
@@ -76,12 +76,12 @@ export class Extension implements StringifyExtension {
7676
break
7777
case "keyDown":
7878
out.appendLine(
79-
`await userEvent.keyboard(${JSON.stringify(`{${step.key}>}`)})`,
79+
`await userEvent.keyboard(${formatAsJSLiteral(`{${step.key}>}`)})`,
8080
)
8181
break
8282
case "keyUp":
8383
out.appendLine(
84-
`await userEvent.keyboard(${JSON.stringify(`{/${step.key}}`)})`,
84+
`await userEvent.keyboard(${formatAsJSLiteral(`{/${step.key}}`)})`,
8585
)
8686
break
8787
case "navigate":
@@ -95,7 +95,7 @@ export class Extension implements StringifyExtension {
9595
}
9696
if (title) {
9797
out.appendLine(
98-
`expect(document.title).toBe(${JSON.stringify(title)})`,
98+
`expect(document.title).toBe(${formatAsJSLiteral(title)})`,
9999
)
100100
}
101101
}
@@ -121,13 +121,17 @@ export class Extension implements StringifyExtension {
121121
}
122122
}
123123

124+
function formatAsJSLiteral(value: string) {
125+
return `"${value.replace(/"/g, '\\"')}"`
126+
}
127+
124128
export function stringifySelector(selector: Selector) {
125129
const selectorString = Array.isArray(selector) ? selector[0] : selector
126130

127131
if (selectorString.startsWith("aria/")) {
128-
return `screen.getByText(${JSON.stringify(selectorString.slice(5))})`
132+
return `screen.getByText(${formatAsJSLiteral(selectorString.slice(5))})`
129133
} else {
130-
return `document.querySelector(${JSON.stringify(selectorString)})`
134+
return `document.querySelector(${formatAsJSLiteral(selectorString)})`
131135
}
132136
}
133137

0 commit comments

Comments
 (0)