customElement.spec.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676
  1. import {
  2. defineAsyncComponent,
  3. defineComponent,
  4. defineCustomElement,
  5. h,
  6. inject,
  7. nextTick,
  8. Ref,
  9. ref,
  10. renderSlot,
  11. VueElement
  12. } from '../src'
  13. describe('defineCustomElement', () => {
  14. const container = document.createElement('div')
  15. document.body.appendChild(container)
  16. beforeEach(() => {
  17. container.innerHTML = ''
  18. })
  19. describe('mounting/unmount', () => {
  20. const E = defineCustomElement({
  21. props: {
  22. msg: {
  23. type: String,
  24. default: 'hello'
  25. }
  26. },
  27. render() {
  28. return h('div', this.msg)
  29. }
  30. })
  31. customElements.define('my-element', E)
  32. test('should work', () => {
  33. container.innerHTML = `<my-element></my-element>`
  34. const e = container.childNodes[0] as VueElement
  35. expect(e).toBeInstanceOf(E)
  36. expect(e._instance).toBeTruthy()
  37. expect(e.shadowRoot!.innerHTML).toBe(`<div>hello</div>`)
  38. })
  39. test('should work w/ manual instantiation', () => {
  40. const e = new E({ msg: 'inline' })
  41. // should lazy init
  42. expect(e._instance).toBe(null)
  43. // should initialize on connect
  44. container.appendChild(e)
  45. expect(e._instance).toBeTruthy()
  46. expect(e.shadowRoot!.innerHTML).toBe(`<div>inline</div>`)
  47. })
  48. test('should unmount on remove', async () => {
  49. container.innerHTML = `<my-element></my-element>`
  50. const e = container.childNodes[0] as VueElement
  51. container.removeChild(e)
  52. await nextTick()
  53. expect(e._instance).toBe(null)
  54. expect(e.shadowRoot!.innerHTML).toBe('')
  55. })
  56. test('should not unmount on move', async () => {
  57. container.innerHTML = `<div><my-element></my-element></div>`
  58. const e = container.childNodes[0].childNodes[0] as VueElement
  59. const i = e._instance
  60. // moving from one parent to another - this will trigger both disconnect
  61. // and connected callbacks synchronously
  62. container.appendChild(e)
  63. await nextTick()
  64. // should be the same instance
  65. expect(e._instance).toBe(i)
  66. expect(e.shadowRoot!.innerHTML).toBe('<div>hello</div>')
  67. })
  68. test('remove then insert again', async () => {
  69. container.innerHTML = `<my-element></my-element>`
  70. const e = container.childNodes[0] as VueElement
  71. container.removeChild(e)
  72. await nextTick()
  73. expect(e._instance).toBe(null)
  74. expect(e.shadowRoot!.innerHTML).toBe('')
  75. container.appendChild(e)
  76. expect(e._instance).toBeTruthy()
  77. expect(e.shadowRoot!.innerHTML).toBe('<div>hello</div>')
  78. })
  79. })
  80. describe('props', () => {
  81. const E = defineCustomElement({
  82. props: ['foo', 'bar', 'bazQux'],
  83. render() {
  84. return [
  85. h('div', null, this.foo),
  86. h('div', null, this.bazQux || (this.bar && this.bar.x))
  87. ]
  88. }
  89. })
  90. customElements.define('my-el-props', E)
  91. test('props via attribute', async () => {
  92. // bazQux should map to `baz-qux` attribute
  93. container.innerHTML = `<my-el-props foo="hello" baz-qux="bye"></my-el-props>`
  94. const e = container.childNodes[0] as VueElement
  95. expect(e.shadowRoot!.innerHTML).toBe('<div>hello</div><div>bye</div>')
  96. // change attr
  97. e.setAttribute('foo', 'changed')
  98. await nextTick()
  99. expect(e.shadowRoot!.innerHTML).toBe('<div>changed</div><div>bye</div>')
  100. e.setAttribute('baz-qux', 'changed')
  101. await nextTick()
  102. expect(e.shadowRoot!.innerHTML).toBe(
  103. '<div>changed</div><div>changed</div>'
  104. )
  105. })
  106. test('props via properties', async () => {
  107. const e = new E()
  108. e.foo = 'one'
  109. e.bar = { x: 'two' }
  110. container.appendChild(e)
  111. expect(e.shadowRoot!.innerHTML).toBe('<div>one</div><div>two</div>')
  112. // reflect
  113. // should reflect primitive value
  114. expect(e.getAttribute('foo')).toBe('one')
  115. // should not reflect rich data
  116. expect(e.hasAttribute('bar')).toBe(false)
  117. e.foo = 'three'
  118. await nextTick()
  119. expect(e.shadowRoot!.innerHTML).toBe('<div>three</div><div>two</div>')
  120. expect(e.getAttribute('foo')).toBe('three')
  121. e.foo = null
  122. await nextTick()
  123. expect(e.shadowRoot!.innerHTML).toBe('<div></div><div>two</div>')
  124. expect(e.hasAttribute('foo')).toBe(false)
  125. e.bazQux = 'four'
  126. await nextTick()
  127. expect(e.shadowRoot!.innerHTML).toBe('<div></div><div>four</div>')
  128. expect(e.getAttribute('baz-qux')).toBe('four')
  129. })
  130. test('attribute -> prop type casting', async () => {
  131. const E = defineCustomElement({
  132. props: {
  133. fooBar: Number, // test casting of camelCase prop names
  134. bar: Boolean,
  135. baz: String
  136. },
  137. render() {
  138. return [
  139. this.fooBar,
  140. typeof this.fooBar,
  141. this.bar,
  142. typeof this.bar,
  143. this.baz,
  144. typeof this.baz
  145. ].join(' ')
  146. }
  147. })
  148. customElements.define('my-el-props-cast', E)
  149. container.innerHTML = `<my-el-props-cast foo-bar="1" baz="12345"></my-el-props-cast>`
  150. const e = container.childNodes[0] as VueElement
  151. expect(e.shadowRoot!.innerHTML).toBe(
  152. `1 number false boolean 12345 string`
  153. )
  154. e.setAttribute('bar', '')
  155. await nextTick()
  156. expect(e.shadowRoot!.innerHTML).toBe(`1 number true boolean 12345 string`)
  157. e.setAttribute('foo-bar', '2e1')
  158. await nextTick()
  159. expect(e.shadowRoot!.innerHTML).toBe(
  160. `20 number true boolean 12345 string`
  161. )
  162. e.setAttribute('baz', '2e1')
  163. await nextTick()
  164. expect(e.shadowRoot!.innerHTML).toBe(`20 number true boolean 2e1 string`)
  165. })
  166. // #4772
  167. test('attr casting w/ programmatic creation', () => {
  168. const E = defineCustomElement({
  169. props: {
  170. foo: Number
  171. },
  172. render() {
  173. return `foo type: ${typeof this.foo}`
  174. }
  175. })
  176. customElements.define('my-element-programmatic', E)
  177. const el = document.createElement('my-element-programmatic') as any
  178. el.setAttribute('foo', '123')
  179. container.appendChild(el)
  180. expect(el.shadowRoot.innerHTML).toBe(`foo type: number`)
  181. })
  182. test('handling properties set before upgrading', () => {
  183. const E = defineCustomElement({
  184. props: {
  185. foo: String,
  186. dataAge: Number
  187. },
  188. setup(props) {
  189. expect(props.foo).toBe('hello')
  190. expect(props.dataAge).toBe(5)
  191. },
  192. render() {
  193. return h('div', `foo: ${this.foo}`)
  194. }
  195. })
  196. const el = document.createElement('my-el-upgrade') as any
  197. el.foo = 'hello'
  198. el.dataset.age = 5
  199. el.notProp = 1
  200. container.appendChild(el)
  201. customElements.define('my-el-upgrade', E)
  202. expect(el.shadowRoot.firstChild.innerHTML).toBe(`foo: hello`)
  203. // should not reflect if not declared as a prop
  204. expect(el.hasAttribute('not-prop')).toBe(false)
  205. })
  206. test('handle properties set before connecting', () => {
  207. const obj = { a: 1 }
  208. const E = defineCustomElement({
  209. props: {
  210. foo: String,
  211. post: Object
  212. },
  213. setup(props) {
  214. expect(props.foo).toBe('hello')
  215. expect(props.post).toBe(obj)
  216. },
  217. render() {
  218. return JSON.stringify(this.post)
  219. }
  220. })
  221. customElements.define('my-el-preconnect', E)
  222. const el = document.createElement('my-el-preconnect') as any
  223. el.foo = 'hello'
  224. el.post = obj
  225. container.appendChild(el)
  226. expect(el.shadowRoot.innerHTML).toBe(JSON.stringify(obj))
  227. })
  228. // https://github.com/vuejs/core/issues/6163
  229. test('handle components with no props', async () => {
  230. const E = defineCustomElement({
  231. render() {
  232. return h('div', 'foo')
  233. }
  234. })
  235. customElements.define('my-element-noprops', E)
  236. const el = document.createElement('my-element-noprops')
  237. container.appendChild(el)
  238. await nextTick()
  239. expect(el.shadowRoot!.innerHTML).toMatchInlineSnapshot('"<div>foo</div>"')
  240. })
  241. // # 5793
  242. test('set number value in dom property', () => {
  243. const E = defineCustomElement({
  244. props: {
  245. 'max-age': Number
  246. },
  247. render() {
  248. // @ts-ignore
  249. return `max age: ${this.maxAge}/type: ${typeof this.maxAge}`
  250. }
  251. })
  252. customElements.define('my-element-number-property', E)
  253. const el = document.createElement('my-element-number-property') as any
  254. container.appendChild(el)
  255. el.maxAge = 50
  256. expect(el.maxAge).toBe(50)
  257. expect(el.shadowRoot.innerHTML).toBe('max age: 50/type: number')
  258. })
  259. })
  260. describe('attrs', () => {
  261. const E = defineCustomElement({
  262. render() {
  263. return [h('div', null, this.$attrs.foo as string)]
  264. }
  265. })
  266. customElements.define('my-el-attrs', E)
  267. test('attrs via attribute', async () => {
  268. container.innerHTML = `<my-el-attrs foo="hello"></my-el-attrs>`
  269. const e = container.childNodes[0] as VueElement
  270. expect(e.shadowRoot!.innerHTML).toBe('<div>hello</div>')
  271. e.setAttribute('foo', 'changed')
  272. await nextTick()
  273. expect(e.shadowRoot!.innerHTML).toBe('<div>changed</div>')
  274. })
  275. test('non-declared properties should not show up in $attrs', () => {
  276. const e = new E()
  277. // @ts-ignore
  278. e.foo = '123'
  279. container.appendChild(e)
  280. expect(e.shadowRoot!.innerHTML).toBe('<div></div>')
  281. })
  282. })
  283. describe('emits', () => {
  284. const CompDef = defineComponent({
  285. setup(_, { emit }) {
  286. emit('created')
  287. return () =>
  288. h('div', {
  289. onClick: () => {
  290. emit('my-click', 1)
  291. },
  292. onMousedown: () => {
  293. emit('myEvent', 1) // validate hypenization
  294. }
  295. })
  296. }
  297. })
  298. const E = defineCustomElement(CompDef)
  299. customElements.define('my-el-emits', E)
  300. test('emit on connect', () => {
  301. const e = new E()
  302. const spy = jest.fn()
  303. e.addEventListener('created', spy)
  304. container.appendChild(e)
  305. expect(spy).toHaveBeenCalled()
  306. })
  307. test('emit on interaction', () => {
  308. container.innerHTML = `<my-el-emits></my-el-emits>`
  309. const e = container.childNodes[0] as VueElement
  310. const spy = jest.fn()
  311. e.addEventListener('my-click', spy)
  312. e.shadowRoot!.childNodes[0].dispatchEvent(new CustomEvent('click'))
  313. expect(spy).toHaveBeenCalledTimes(1)
  314. expect(spy.mock.calls[0][0]).toMatchObject({
  315. detail: [1]
  316. })
  317. })
  318. // #5373
  319. test('case transform for camelCase event', () => {
  320. container.innerHTML = `<my-el-emits></my-el-emits>`
  321. const e = container.childNodes[0] as VueElement
  322. const spy1 = jest.fn()
  323. e.addEventListener('myEvent', spy1)
  324. const spy2 = jest.fn()
  325. // emitting myEvent, but listening for my-event. This happens when
  326. // using the custom element in a Vue template
  327. e.addEventListener('my-event', spy2)
  328. e.shadowRoot!.childNodes[0].dispatchEvent(new CustomEvent('mousedown'))
  329. expect(spy1).toHaveBeenCalledTimes(1)
  330. expect(spy2).toHaveBeenCalledTimes(1)
  331. })
  332. test('emit from within async component wrapper', async () => {
  333. const E = defineCustomElement(
  334. defineAsyncComponent(
  335. () => new Promise<typeof CompDef>(res => res(CompDef as any))
  336. )
  337. )
  338. customElements.define('my-async-el-emits', E)
  339. container.innerHTML = `<my-async-el-emits></my-async-el-emits>`
  340. const e = container.childNodes[0] as VueElement
  341. const spy = jest.fn()
  342. e.addEventListener('my-click', spy)
  343. // this feels brittle but seems necessary to reach the node in the DOM.
  344. await customElements.whenDefined('my-async-el-emits')
  345. e.shadowRoot!.childNodes[0].dispatchEvent(new CustomEvent('click'))
  346. expect(spy).toHaveBeenCalled()
  347. expect(spy.mock.calls[0][0]).toMatchObject({
  348. detail: [1]
  349. })
  350. })
  351. })
  352. describe('slots', () => {
  353. const E = defineCustomElement({
  354. render() {
  355. return [
  356. h('div', null, [
  357. renderSlot(this.$slots, 'default', undefined, () => [
  358. h('div', 'fallback')
  359. ])
  360. ]),
  361. h('div', null, renderSlot(this.$slots, 'named'))
  362. ]
  363. }
  364. })
  365. customElements.define('my-el-slots', E)
  366. test('default slot', () => {
  367. container.innerHTML = `<my-el-slots><span>hi</span></my-el-slots>`
  368. const e = container.childNodes[0] as VueElement
  369. // native slots allocation does not affect innerHTML, so we just
  370. // verify that we've rendered the correct native slots here...
  371. expect(e.shadowRoot!.innerHTML).toBe(
  372. `<div><slot><div>fallback</div></slot></div><div><slot name="named"></slot></div>`
  373. )
  374. })
  375. })
  376. describe('provide/inject', () => {
  377. const Consumer = defineCustomElement({
  378. setup() {
  379. const foo = inject<Ref>('foo')!
  380. return () => h('div', foo.value)
  381. }
  382. })
  383. customElements.define('my-consumer', Consumer)
  384. test('over nested usage', async () => {
  385. const foo = ref('injected!')
  386. const Provider = defineCustomElement({
  387. provide: {
  388. foo
  389. },
  390. render() {
  391. return h('my-consumer')
  392. }
  393. })
  394. customElements.define('my-provider', Provider)
  395. container.innerHTML = `<my-provider><my-provider>`
  396. const provider = container.childNodes[0] as VueElement
  397. const consumer = provider.shadowRoot!.childNodes[0] as VueElement
  398. expect(consumer.shadowRoot!.innerHTML).toBe(`<div>injected!</div>`)
  399. foo.value = 'changed!'
  400. await nextTick()
  401. expect(consumer.shadowRoot!.innerHTML).toBe(`<div>changed!</div>`)
  402. })
  403. test('over slot composition', async () => {
  404. const foo = ref('injected!')
  405. const Provider = defineCustomElement({
  406. provide: {
  407. foo
  408. },
  409. render() {
  410. return renderSlot(this.$slots, 'default')
  411. }
  412. })
  413. customElements.define('my-provider-2', Provider)
  414. container.innerHTML = `<my-provider-2><my-consumer></my-consumer><my-provider-2>`
  415. const provider = container.childNodes[0]
  416. const consumer = provider.childNodes[0] as VueElement
  417. expect(consumer.shadowRoot!.innerHTML).toBe(`<div>injected!</div>`)
  418. foo.value = 'changed!'
  419. await nextTick()
  420. expect(consumer.shadowRoot!.innerHTML).toBe(`<div>changed!</div>`)
  421. })
  422. test('inherited from ancestors', async () => {
  423. const fooA = ref('FooA!')
  424. const fooB = ref('FooB!')
  425. const ProviderA = defineCustomElement({
  426. provide: {
  427. fooA
  428. },
  429. render() {
  430. return h('provider-b')
  431. }
  432. })
  433. const ProviderB = defineCustomElement({
  434. provide: {
  435. fooB
  436. },
  437. render() {
  438. return h('my-multi-consumer')
  439. }
  440. })
  441. const Consumer = defineCustomElement({
  442. setup() {
  443. const fooA = inject<Ref>('fooA')!
  444. const fooB = inject<Ref>('fooB')!
  445. return () => h('div', `${fooA.value} ${fooB.value}`)
  446. }
  447. })
  448. customElements.define('provider-a', ProviderA)
  449. customElements.define('provider-b', ProviderB)
  450. customElements.define('my-multi-consumer', Consumer)
  451. container.innerHTML = `<provider-a><provider-a>`
  452. const providerA = container.childNodes[0] as VueElement
  453. const providerB = providerA.shadowRoot!.childNodes[0] as VueElement
  454. const consumer = providerB.shadowRoot!.childNodes[0] as VueElement
  455. expect(consumer.shadowRoot!.innerHTML).toBe(`<div>FooA! FooB!</div>`)
  456. fooA.value = 'changedA!'
  457. fooB.value = 'changedB!'
  458. await nextTick()
  459. expect(consumer.shadowRoot!.innerHTML).toBe(
  460. `<div>changedA! changedB!</div>`
  461. )
  462. })
  463. })
  464. describe('styles', () => {
  465. test('should attach styles to shadow dom', () => {
  466. const Foo = defineCustomElement({
  467. styles: [`div { color: red; }`],
  468. render() {
  469. return h('div', 'hello')
  470. }
  471. })
  472. customElements.define('my-el-with-styles', Foo)
  473. container.innerHTML = `<my-el-with-styles></my-el-with-styles>`
  474. const el = container.childNodes[0] as VueElement
  475. const style = el.shadowRoot?.querySelector('style')!
  476. expect(style.textContent).toBe(`div { color: red; }`)
  477. })
  478. })
  479. describe('async', () => {
  480. test('should work', async () => {
  481. const loaderSpy = jest.fn()
  482. const E = defineCustomElement(
  483. defineAsyncComponent(() => {
  484. loaderSpy()
  485. return Promise.resolve({
  486. props: ['msg'],
  487. styles: [`div { color: red }`],
  488. render(this: any) {
  489. return h('div', null, this.msg)
  490. }
  491. })
  492. })
  493. )
  494. customElements.define('my-el-async', E)
  495. container.innerHTML =
  496. `<my-el-async msg="hello"></my-el-async>` +
  497. `<my-el-async msg="world"></my-el-async>`
  498. await new Promise(r => setTimeout(r))
  499. // loader should be called only once
  500. expect(loaderSpy).toHaveBeenCalledTimes(1)
  501. const e1 = container.childNodes[0] as VueElement
  502. const e2 = container.childNodes[1] as VueElement
  503. // should inject styles
  504. expect(e1.shadowRoot!.innerHTML).toBe(
  505. `<style>div { color: red }</style><div>hello</div>`
  506. )
  507. expect(e2.shadowRoot!.innerHTML).toBe(
  508. `<style>div { color: red }</style><div>world</div>`
  509. )
  510. // attr
  511. e1.setAttribute('msg', 'attr')
  512. await nextTick()
  513. expect((e1 as any).msg).toBe('attr')
  514. expect(e1.shadowRoot!.innerHTML).toBe(
  515. `<style>div { color: red }</style><div>attr</div>`
  516. )
  517. // props
  518. expect(`msg` in e1).toBe(true)
  519. ;(e1 as any).msg = 'prop'
  520. expect(e1.getAttribute('msg')).toBe('prop')
  521. expect(e1.shadowRoot!.innerHTML).toBe(
  522. `<style>div { color: red }</style><div>prop</div>`
  523. )
  524. })
  525. test('set DOM property before resolve', async () => {
  526. const E = defineCustomElement(
  527. defineAsyncComponent(() => {
  528. return Promise.resolve({
  529. props: ['msg'],
  530. setup(props) {
  531. expect(typeof props.msg).toBe('string')
  532. },
  533. render(this: any) {
  534. return h('div', this.msg)
  535. }
  536. })
  537. })
  538. )
  539. customElements.define('my-el-async-2', E)
  540. const e1 = new E()
  541. // set property before connect
  542. e1.msg = 'hello'
  543. const e2 = new E()
  544. container.appendChild(e1)
  545. container.appendChild(e2)
  546. // set property after connect but before resolve
  547. e2.msg = 'world'
  548. await new Promise(r => setTimeout(r))
  549. expect(e1.shadowRoot!.innerHTML).toBe(`<div>hello</div>`)
  550. expect(e2.shadowRoot!.innerHTML).toBe(`<div>world</div>`)
  551. e1.msg = 'world'
  552. expect(e1.shadowRoot!.innerHTML).toBe(`<div>world</div>`)
  553. e2.msg = 'hello'
  554. expect(e2.shadowRoot!.innerHTML).toBe(`<div>hello</div>`)
  555. })
  556. test('Number prop casting before resolve', async () => {
  557. const E = defineCustomElement(
  558. defineAsyncComponent(() => {
  559. return Promise.resolve({
  560. props: { n: Number },
  561. setup(props) {
  562. expect(props.n).toBe(20)
  563. },
  564. render(this: any) {
  565. return h('div', this.n + ',' + typeof this.n)
  566. }
  567. })
  568. })
  569. )
  570. customElements.define('my-el-async-3', E)
  571. container.innerHTML = `<my-el-async-3 n="2e1"></my-el-async-3>`
  572. await new Promise(r => setTimeout(r))
  573. const e = container.childNodes[0] as VueElement
  574. expect(e.shadowRoot!.innerHTML).toBe(`<div>20,number</div>`)
  575. })
  576. test('with slots', async () => {
  577. const E = defineCustomElement(
  578. defineAsyncComponent(() => {
  579. return Promise.resolve({
  580. render(this: any) {
  581. return [
  582. h('div', null, [
  583. renderSlot(this.$slots, 'default', undefined, () => [
  584. h('div', 'fallback')
  585. ])
  586. ]),
  587. h('div', null, renderSlot(this.$slots, 'named'))
  588. ]
  589. }
  590. })
  591. })
  592. )
  593. customElements.define('my-el-async-slots', E)
  594. container.innerHTML = `<my-el-async-slots><span>hi</span></my-el-async-slots>`
  595. await new Promise(r => setTimeout(r))
  596. const e = container.childNodes[0] as VueElement
  597. expect(e.shadowRoot!.innerHTML).toBe(
  598. `<div><slot><div>fallback</div></slot></div><div><slot name="named"></slot></div>`
  599. )
  600. })
  601. })
  602. })