-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathreact-to-webcomponent.test.jsx
596 lines (493 loc) · 15.8 KB
/
react-to-webcomponent.test.jsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
/* eslint-disable react-hooks/rules-of-hooks */
/* eslint-disable no-console */
import { test, assert, expect, beforeEach, describe } from "vitest"
import React from "react"
import PropTypes from "prop-types"
import { CamelCaseGreeting, Greeting } from "./components"
import reactToWebComponent from "../legacy/react-to-webcomponent"
const reactEnv = __dirname.replace(/.*?([^\\/]+\d+).*/g, "$1")
// reactEnv = "react16" | "react17" | "react18" | "preact10"
const requeueIfTruthy = (fn, maxChecks = 100) => {
let runCount = 0
return new Promise((r) => {
const waitInterval = setInterval(() => {
try {
const requeue = fn()
runCount++
if (!requeue) {
clearInterval(waitInterval)
r(runCount)
} else if (runCount >= maxChecks) {
clearInterval(waitInterval)
console.log(
"Max truthy checks reached, test never became ready:",
fn.toString(),
{ reactEnv, runCount, maxChecks },
)
r(runCount)
}
} catch (err) {
clearInterval(waitInterval)
console.log("!! Threw at requeue function: ", fn.toString(), {
reactEnv,
runCount,
maxChecks,
err,
})
setTimeout(() => {
throw err // wait until next frame to rethrow or else the console log information above gets swallowed
}, 0)
}
}, 0)
})
}
describe("react-to-webcomponent", () => {
beforeEach(() => {
document.body.innerHTML = ""
})
test("basics with react", () => {
const MyWelcome = reactToWebComponent(Greeting)
customElements.define("my-welcome", MyWelcome)
const myWelcome = new MyWelcome()
document.getElementsByTagName("body")[0].appendChild(myWelcome)
expect(myWelcome.nodeName).toEqual("MY-WELCOME")
})
test("works with attributes set with propTypes", async () => {
expect.assertions(1)
Greeting.propTypes = {
name: PropTypes.string.isRequired,
}
const MyGreeting = reactToWebComponent(Greeting)
customElements.define("my-greeting", MyGreeting)
console.error = function (...messages) {
assert.ok(
messages.some((message) => message.includes("required")),
"got a warning with required",
)
}
const body = document.body
body.innerHTML = "<my-greeting name='Christopher'></my-greeting>"
await requeueIfTruthy(() => {
if (!body.firstElementChild.innerHTML) {
return true
}
expect(body.firstElementChild.innerHTML).toEqual(
"<h1>Hello, Christopher</h1>",
)
})
})
test("works with shadow DOM `options.shadow === true`", async () => {
expect.assertions(5)
const MyWelcome = reactToWebComponent(Greeting, {
shadow: true,
})
customElements.define("my-shadow-welcome", MyWelcome)
const body = document.body
const myWelcome = new MyWelcome()
body.appendChild(myWelcome)
await requeueIfTruthy(() => {
if (!myWelcome.shadowRoot || !myWelcome.shadowRoot.children.length) {
return true
}
expect(myWelcome.shadowRoot).not.toEqual(undefined)
expect(myWelcome.shadowRoot.children.length).toEqual(1)
const child = myWelcome.shadowRoot.childNodes[0]
expect(child.tagName).toEqual("H1")
expect(child.innerHTML).toEqual("Hello, ")
myWelcome.name = "Justin"
})
await requeueIfTruthy(() => {
const child = myWelcome.shadowRoot.childNodes[0]
if (!child.innerHTML) {
return true
}
expect(child.innerHTML, "Hello, Justin")
})
})
test('It works without shadow option set to "true"', async () => {
expect.assertions(1)
const MyWelcome = reactToWebComponent(Greeting)
customElements.define("my-noshadow-welcome", MyWelcome)
const body = document.body
const myWelcome = new MyWelcome()
body.appendChild(myWelcome)
await new Promise((r) => {
setTimeout(() => {
expect(myWelcome.shadowRoot).toEqual(null)
r()
}, 0)
})
})
test("It converts dashed-attributes to camelCase", async () => {
expect.assertions(1)
CamelCaseGreeting.propTypes = {
camelCaseName: PropTypes.string.isRequired,
}
const MyGreeting = reactToWebComponent(CamelCaseGreeting, {})
customElements.define("my-dashed-style-greeting", MyGreeting)
const body = document.body
console.error = function (...messages) {
assert.ok(
messages.some((message) => message.includes("required")),
"got a warning with required",
)
}
body.innerHTML =
"<my-dashed-style-greeting camel-case-name='Christopher'></my-dashed-style-greeting>"
await requeueIfTruthy(() => {
if (!body.firstElementChild.innerHTML) {
return true
}
expect(body.firstElementChild.innerHTML).toEqual(
"<h1>Hello, Christopher</h1>",
)
})
})
test("mounts and unmounts underlying react functional component", async () => {
if (reactEnv === "preact10") {
expect.assertions(0)
// does not work in preact - useEffect and the returned fn do not run on mount/unmount
return
}
expect.assertions(2)
await new Promise((r) => {
function TestComponent() {
React.useEffect(() => {
// code here runs on mount
expect(true)
return () => {
// code here runs on unmount
expect(true)
r()
}
}, [])
return <h1>Hello, Goodbye</h1>
}
class WebCom extends reactToWebComponent(TestComponent, {}) {}
customElements.define("mount-unmount-func", WebCom)
const webCom = new WebCom()
const body = document.body
setTimeout(() => {
body.appendChild(webCom)
setTimeout(() => {
body.removeChild(webCom)
}, 0)
}, 0)
})
})
test("mounts and unmounts underlying react class component", async () => {
// also works in preact
expect.assertions(2)
await new Promise((r) => {
class RCom extends React.Component {
componentDidMount() {
expect(true)
}
componentWillUnmount() {
expect(true)
r()
}
render() {
return <h1>Hello, Goodbye</h1>
}
}
class WebCom extends reactToWebComponent(RCom) {}
customElements.define("mount-unmount", WebCom)
const webCom = new WebCom()
const body = document.body
setTimeout(() => {
body.appendChild(webCom)
setTimeout(() => {
body.removeChild(webCom)
})
}, 0)
})
})
test("options.props can be used as an array of props instead of relying on keys from propTypes", async () => {
expect.assertions(1)
function PropTypesNotRequired({ greeting, camelCaseName }) {
return (
<h1>
{greeting}, {camelCaseName}
</h1>
)
}
const WebPropTypesNotRequired = reactToWebComponent(PropTypesNotRequired, {
props: ["greeting", "camelCaseName"],
})
customElements.define("web-proptypes-not-required", WebPropTypesNotRequired)
const body = document.body
body.innerHTML =
"<web-proptypes-not-required greeting='Ayy' camel-case-name='lmao'></web-proptypes-not-required>"
await requeueIfTruthy(() => {
if (!body.firstElementChild.innerHTML) {
return true
}
expect(body.firstElementChild.innerHTML).toEqual("<h1>Ayy, lmao</h1>")
})
})
test("options.props can specify and will convert the String attribute value into Number, Boolean, Array, and/or Object", async () => {
expect.assertions(12)
function OptionsPropsTypeCasting({
stringProp,
numProp,
floatProp,
trueProp,
falseProp,
arrayProp,
objProp,
}) {
global.castedValues = {
stringProp,
numProp,
floatProp,
trueProp,
falseProp,
arrayProp,
objProp,
}
return <h1>{stringProp}</h1>
}
OptionsPropsTypeCasting.propTypes = {
stringProp: PropTypes.string.isRequired,
numProp: PropTypes.number.isRequired,
floatProp: PropTypes.number.isRequired,
trueProp: PropTypes.bool.isRequired,
falseProp: PropTypes.bool.isRequired,
arrayProp: PropTypes.array.isRequired,
objProp: PropTypes.object.isRequired,
}
const WebOptionsPropsTypeCasting = reactToWebComponent(
OptionsPropsTypeCasting,
{
props: {
stringProp: "string",
numProp: "number",
floatProp: "number",
trueProp: "boolean",
falseProp: "boolean",
arrayProp: "array",
objProp: "object",
},
},
)
customElements.define("attr-type-casting", WebOptionsPropsTypeCasting)
const body = document.body
console.error = function (...messages) {
// propTypes will throw if any of the types passed into the underlying react component are wrong or missing
expect("propTypes should not have thrown").toEqual(messages.join(""))
}
body.innerHTML = `
<attr-type-casting
string-prop="iloveyou"
num-prop="360"
float-prop="0.5"
true-prop="true"
false-prop="false"
array-prop='[true, 100.25, "👽", { "aliens": "welcome" }]'
obj-prop='{ "very": "object", "such": "wow!" }'
></attr-type-casting>
`
await requeueIfTruthy(() => {
if (!body.firstElementChild.innerHTML) {
return true
}
const {
stringProp,
numProp,
floatProp,
trueProp,
falseProp,
arrayProp,
objProp,
} = global.castedValues
expect(stringProp).toEqual("iloveyou")
expect(numProp).toEqual(360)
expect(floatProp).toEqual(0.5)
expect(trueProp).toEqual(true)
expect(falseProp).toEqual(false)
expect(arrayProp.length).toEqual(4)
expect(arrayProp[0]).toEqual(true)
expect(arrayProp[1]).toEqual(100.25)
expect(arrayProp[2]).toEqual("👽")
expect(arrayProp[3].aliens).toEqual("welcome")
expect(objProp.very).toEqual("object")
expect(objProp.such).toEqual("wow!")
})
})
test("Props typed as Function convert the string value of attribute into global fn calls bound to the webcomponent instance", async () => {
expect.assertions(2)
function ThemeSelect({ handleClick }) {
return (
<div>
<button onClick={() => handleClick("V")}>V</button>
<button onClick={() => handleClick("Johnny")}>Johnny</button>
<button onClick={() => handleClick("Jane")}>Jane</button>
</div>
)
}
ThemeSelect.propTypes = {
handleClick: PropTypes.func.isRequired,
}
const WebThemeSelect = reactToWebComponent(ThemeSelect, {
props: {
handleClick: "function",
},
})
customElements.define("theme-select", WebThemeSelect)
const body = document.body
await new Promise((r) => {
const failUnlessCleared = setTimeout(() => {
delete global.globalFn
expect("globalFn was not called to clear the failure timeout").toEqual(
"not to fail because globalFn should have been called to clear the failure timeout",
)
r()
}, 1000)
global.globalFn = function (selected) {
delete global.globalFn
clearTimeout(failUnlessCleared)
expect(selected).toEqual("Jane")
expect(this).toEqual(document.querySelector("theme-select"))
r()
}
body.innerHTML = "<theme-select handle-click='globalFn'></theme-select>"
setTimeout(() => {
document.querySelector("theme-select button:last-child").click()
}, 0)
})
})
test("Props typed as 'ref' work with functional components", async () => {
const notPreact = reactEnv !== "preact10" // preact doesn't have useImperativeHandle so no ref to functional components directly
expect.assertions(notPreact ? 6 : 7)
const RCom = React.forwardRef(function RCom(props, ref) {
const [Tag, setTag] = React.useState("h1")
notPreact &&
React.useImperativeHandle(ref, () => ({
Tag,
setTag,
}))
return (
<Tag ref={props.h1Ref} onClick={() => setTag("h2")}>
Ref
</Tag>
)
})
class WebCom extends reactToWebComponent(RCom, {
props: {
ref: "ref",
h1Ref: "ref",
},
}) {}
customElements.define("ref-test-func", WebCom)
const body = document.body
await new Promise((r) => {
body.innerHTML = "<ref-test-func ref h1-ref></ref-test-func>"
setTimeout(() => {
const el = document.querySelector("ref-test-func")
notPreact && expect(el.ref.current.Tag).toEqual("h1")
notPreact && expect(typeof el.ref.current.setTag).toEqual("function")
const h1 = document.querySelector("ref-test-func h1")
expect(el.h1Ref.current).toEqual(h1)
h1.click()
setTimeout(() => {
const h2 = document.querySelector("ref-test-func h2")
notPreact && expect(el.ref.current.Tag).toEqual("h2")
expect(el.h1Ref.current).not.toEqual(h1)
expect(el.h1Ref.current).toEqual(h2)
r()
}, 0)
}, 0)
})
})
test("Props typed as 'ref' work with class components", async () => {
expect.assertions(4) // full functionality with class components works in preact too
class RCom extends React.Component {
constructor(props) {
super(props)
this.state = { tag: "h1" }
}
render() {
const Tag = this.state.tag
return (
<Tag
ref={this.props.h1Ref}
onClick={() => this.setState({ tag: "h2" })}
>
Ref
</Tag>
)
}
}
class WebCom extends reactToWebComponent(RCom, {
props: {
ref: "ref",
h1Ref: "ref",
},
}) {}
customElements.define("ref-test", WebCom)
const body = document.body
await new Promise((r) => {
body.innerHTML = "<ref-test ref h1-ref></ref-test>"
setTimeout(() => {
const el = document.querySelector("ref-test")
expect(el.ref.current instanceof RCom).toEqual(true)
const h1 = document.querySelector("ref-test h1")
expect(el.h1Ref.current).toEqual(h1)
h1.click()
setTimeout(() => {
const h2 = document.querySelector("ref-test h2")
expect(el.h1Ref.current).not.toEqual(h1)
expect(el.h1Ref.current).toEqual(h2)
r()
}, 0)
}, 0)
})
})
test("Supports text child nodes", async () => {
function Greeting({ children }) {
return <h1>Hello, {children}</h1>
}
Greeting.propTypes = {
children: PropTypes.node.isRequired,
}
const MyGreeting = reactToWebComponent(Greeting)
customElements.define("greeting-child-text", MyGreeting)
const body = document.body
body.innerHTML = "<greeting-child-text>Christopher</greeting-child-text>"
await new Promise((r) => {
setTimeout(() => {
expect(body.firstElementChild.innerHTML).toEqual(
"<h1>Hello, Christopher</h1>",
)
r()
}, 0)
})
})
test("Supports nested html nodes", async () => {
function Greeting({ name, children }) {
return (
<div>
<h1>Hello, {name}</h1>
{children}
</div>
)
}
Greeting.propTypes = {
name: PropTypes.string.isRequired,
children: PropTypes.node.isRequired,
}
const MyGreeting = reactToWebComponent(Greeting)
customElements.define("child-greeting", MyGreeting)
const body = document.body
body.innerHTML = `<child-greeting name='Christopher'><a href="localhost">Nested child</a></child-greeting>`
await new Promise((r) => {
setTimeout(() => {
expect(body.firstElementChild.innerHTML).toEqual(
`<div><h1>Hello, Christopher</h1><a href="localhost">Nested child</a></div>`,
)
r()
}, 0)
})
})
})