customElement.spec.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  1. import {
  2. defineAsyncComponent,
  3. defineCustomElement,
  4. h,
  5. inject,
  6. nextTick,
  7. Ref,
  8. ref,
  9. renderSlot,
  10. VueElement
  11. } from '../src'
  12. describe('defineCustomElement', () => {
  13. const container = document.createElement('div')
  14. document.body.appendChild(container)
  15. beforeEach(() => {
  16. container.innerHTML = ''
  17. })
  18. describe('mounting/unmount', () => {
  19. const E = defineCustomElement({
  20. props: {
  21. msg: {
  22. type: String,
  23. default: 'hello'
  24. }
  25. },
  26. render() {
  27. return h('div', this.msg)
  28. }
  29. })
  30. customElements.define('my-element', E)
  31. test('should work', () => {
  32. container.innerHTML = `<my-element></my-element>`
  33. const e = container.childNodes[0] as VueElement
  34. expect(e).toBeInstanceOf(E)
  35. expect(e._instance).toBeTruthy()
  36. expect(e.shadowRoot!.innerHTML).toBe(`<div>hello</div>`)
  37. })
  38. test('should work w/ manual instantiation', () => {
  39. const e = new E({ msg: 'inline' })
  40. // should lazy init
  41. expect(e._instance).toBe(null)
  42. // should initialize on connect
  43. container.appendChild(e)
  44. expect(e._instance).toBeTruthy()
  45. expect(e.shadowRoot!.innerHTML).toBe(`<div>inline</div>`)
  46. })
  47. test('should unmount on remove', async () => {
  48. container.innerHTML = `<my-element></my-element>`
  49. const e = container.childNodes[0] as VueElement
  50. container.removeChild(e)
  51. await nextTick()
  52. expect(e._instance).toBe(null)
  53. expect(e.shadowRoot!.innerHTML).toBe('')
  54. })
  55. test('should not unmount on move', async () => {
  56. container.innerHTML = `<div><my-element></my-element></div>`
  57. const e = container.childNodes[0].childNodes[0] as VueElement
  58. const i = e._instance
  59. // moving from one parent to another - this will trigger both disconnect
  60. // and connected callbacks synchronously
  61. container.appendChild(e)
  62. await nextTick()
  63. // should be the same instance
  64. expect(e._instance).toBe(i)
  65. expect(e.shadowRoot!.innerHTML).toBe('<div>hello</div>')
  66. })
  67. })
  68. describe('props', () => {
  69. const E = defineCustomElement({
  70. props: ['foo', 'bar', 'bazQux'],
  71. render() {
  72. return [
  73. h('div', null, this.foo),
  74. h('div', null, this.bazQux || (this.bar && this.bar.x))
  75. ]
  76. }
  77. })
  78. customElements.define('my-el-props', E)
  79. test('props via attribute', async () => {
  80. // bazQux should map to `baz-qux` attribute
  81. container.innerHTML = `<my-el-props foo="hello" baz-qux="bye"></my-el-props>`
  82. const e = container.childNodes[0] as VueElement
  83. expect(e.shadowRoot!.innerHTML).toBe('<div>hello</div><div>bye</div>')
  84. // change attr
  85. e.setAttribute('foo', 'changed')
  86. await nextTick()
  87. expect(e.shadowRoot!.innerHTML).toBe('<div>changed</div><div>bye</div>')
  88. e.setAttribute('baz-qux', 'changed')
  89. await nextTick()
  90. expect(e.shadowRoot!.innerHTML).toBe(
  91. '<div>changed</div><div>changed</div>'
  92. )
  93. })
  94. test('props via properties', async () => {
  95. const e = new E()
  96. e.foo = 'one'
  97. e.bar = { x: 'two' }
  98. container.appendChild(e)
  99. expect(e.shadowRoot!.innerHTML).toBe('<div>one</div><div>two</div>')
  100. // reflect
  101. // should reflect primitive value
  102. expect(e.getAttribute('foo')).toBe('one')
  103. // should not reflect rich data
  104. expect(e.hasAttribute('bar')).toBe(false)
  105. e.foo = 'three'
  106. await nextTick()
  107. expect(e.shadowRoot!.innerHTML).toBe('<div>three</div><div>two</div>')
  108. expect(e.getAttribute('foo')).toBe('three')
  109. e.foo = null
  110. await nextTick()
  111. expect(e.shadowRoot!.innerHTML).toBe('<div></div><div>two</div>')
  112. expect(e.hasAttribute('foo')).toBe(false)
  113. e.bazQux = 'four'
  114. await nextTick()
  115. expect(e.shadowRoot!.innerHTML).toBe('<div></div><div>four</div>')
  116. expect(e.getAttribute('baz-qux')).toBe('four')
  117. })
  118. test('attribute -> prop type casting', async () => {
  119. const E = defineCustomElement({
  120. props: {
  121. fooBar: Number, // test casting of camelCase prop names
  122. bar: Boolean,
  123. baz: String
  124. },
  125. render() {
  126. return [
  127. this.fooBar,
  128. typeof this.fooBar,
  129. this.bar,
  130. typeof this.bar,
  131. this.baz,
  132. typeof this.baz
  133. ].join(' ')
  134. }
  135. })
  136. customElements.define('my-el-props-cast', E)
  137. container.innerHTML = `<my-el-props-cast foo-bar="1" baz="12345"></my-el-props-cast>`
  138. const e = container.childNodes[0] as VueElement
  139. expect(e.shadowRoot!.innerHTML).toBe(
  140. `1 number false boolean 12345 string`
  141. )
  142. e.setAttribute('bar', '')
  143. await nextTick()
  144. expect(e.shadowRoot!.innerHTML).toBe(`1 number true boolean 12345 string`)
  145. e.setAttribute('foo-bar', '2e1')
  146. await nextTick()
  147. expect(e.shadowRoot!.innerHTML).toBe(
  148. `20 number true boolean 12345 string`
  149. )
  150. e.setAttribute('baz', '2e1')
  151. await nextTick()
  152. expect(e.shadowRoot!.innerHTML).toBe(`20 number true boolean 2e1 string`)
  153. })
  154. // #4772
  155. test('attr casting w/ programmatic creation', () => {
  156. const E = defineCustomElement({
  157. props: {
  158. foo: Number
  159. },
  160. render() {
  161. return `foo type: ${typeof this.foo}`
  162. }
  163. })
  164. customElements.define('my-element-programmatic', E)
  165. const el = document.createElement('my-element-programmatic') as any
  166. el.setAttribute('foo', '123')
  167. container.appendChild(el)
  168. expect(el.shadowRoot.innerHTML).toBe(`foo type: number`)
  169. })
  170. test('handling properties set before upgrading', () => {
  171. const E = defineCustomElement({
  172. props: {
  173. foo: String,
  174. dataAge: Number
  175. },
  176. setup(props) {
  177. expect(props.foo).toBe('hello')
  178. expect(props.dataAge).toBe(5)
  179. },
  180. render() {
  181. return `foo: ${this.foo}`
  182. }
  183. })
  184. const el = document.createElement('my-el-upgrade') as any
  185. el.foo = 'hello'
  186. el.dataset.age = 5
  187. container.appendChild(el)
  188. customElements.define('my-el-upgrade', E)
  189. expect(el.shadowRoot.innerHTML).toBe(`foo: hello`)
  190. })
  191. // https://github.com/vuejs/core/issues/6163
  192. test('handle components with no props', async () => {
  193. const E = defineCustomElement({
  194. render() {
  195. return h('div', 'foo')
  196. }
  197. })
  198. customElements.define('my-element-noprops', E)
  199. const el = document.createElement('my-element-noprops')
  200. container.appendChild(el)
  201. await nextTick()
  202. expect(el.shadowRoot!.innerHTML).toMatchInlineSnapshot('"<div>foo</div>"')
  203. })
  204. })
  205. describe('emits', () => {
  206. const E = defineCustomElement({
  207. setup(_, { emit }) {
  208. emit('created')
  209. return () =>
  210. h('div', {
  211. onClick: () => emit('my-click', 1)
  212. })
  213. }
  214. })
  215. customElements.define('my-el-emits', E)
  216. test('emit on connect', () => {
  217. const e = new E()
  218. const spy = jest.fn()
  219. e.addEventListener('created', spy)
  220. container.appendChild(e)
  221. expect(spy).toHaveBeenCalled()
  222. })
  223. test('emit on interaction', () => {
  224. container.innerHTML = `<my-el-emits></my-el-emits>`
  225. const e = container.childNodes[0] as VueElement
  226. const spy = jest.fn()
  227. e.addEventListener('my-click', spy)
  228. e.shadowRoot!.childNodes[0].dispatchEvent(new CustomEvent('click'))
  229. expect(spy).toHaveBeenCalled()
  230. expect(spy.mock.calls[0][0]).toMatchObject({
  231. detail: [1]
  232. })
  233. })
  234. })
  235. describe('slots', () => {
  236. const E = defineCustomElement({
  237. render() {
  238. return [
  239. h('div', null, [
  240. renderSlot(this.$slots, 'default', undefined, () => [
  241. h('div', 'fallback')
  242. ])
  243. ]),
  244. h('div', null, renderSlot(this.$slots, 'named'))
  245. ]
  246. }
  247. })
  248. customElements.define('my-el-slots', E)
  249. test('default slot', () => {
  250. container.innerHTML = `<my-el-slots><span>hi</span></my-el-slots>`
  251. const e = container.childNodes[0] as VueElement
  252. // native slots allocation does not affect innerHTML, so we just
  253. // verify that we've rendered the correct native slots here...
  254. expect(e.shadowRoot!.innerHTML).toBe(
  255. `<div><slot><div>fallback</div></slot></div><div><slot name="named"></slot></div>`
  256. )
  257. })
  258. })
  259. describe('provide/inject', () => {
  260. const Consumer = defineCustomElement({
  261. setup() {
  262. const foo = inject<Ref>('foo')!
  263. return () => h('div', foo.value)
  264. }
  265. })
  266. customElements.define('my-consumer', Consumer)
  267. test('over nested usage', async () => {
  268. const foo = ref('injected!')
  269. const Provider = defineCustomElement({
  270. provide: {
  271. foo
  272. },
  273. render() {
  274. return h('my-consumer')
  275. }
  276. })
  277. customElements.define('my-provider', Provider)
  278. container.innerHTML = `<my-provider><my-provider>`
  279. const provider = container.childNodes[0] as VueElement
  280. const consumer = provider.shadowRoot!.childNodes[0] as VueElement
  281. expect(consumer.shadowRoot!.innerHTML).toBe(`<div>injected!</div>`)
  282. foo.value = 'changed!'
  283. await nextTick()
  284. expect(consumer.shadowRoot!.innerHTML).toBe(`<div>changed!</div>`)
  285. })
  286. test('over slot composition', async () => {
  287. const foo = ref('injected!')
  288. const Provider = defineCustomElement({
  289. provide: {
  290. foo
  291. },
  292. render() {
  293. return renderSlot(this.$slots, 'default')
  294. }
  295. })
  296. customElements.define('my-provider-2', Provider)
  297. container.innerHTML = `<my-provider-2><my-consumer></my-consumer><my-provider-2>`
  298. const provider = container.childNodes[0]
  299. const consumer = provider.childNodes[0] as VueElement
  300. expect(consumer.shadowRoot!.innerHTML).toBe(`<div>injected!</div>`)
  301. foo.value = 'changed!'
  302. await nextTick()
  303. expect(consumer.shadowRoot!.innerHTML).toBe(`<div>changed!</div>`)
  304. })
  305. })
  306. describe('styles', () => {
  307. test('should attach styles to shadow dom', () => {
  308. const Foo = defineCustomElement({
  309. styles: [`div { color: red; }`],
  310. render() {
  311. return h('div', 'hello')
  312. }
  313. })
  314. customElements.define('my-el-with-styles', Foo)
  315. container.innerHTML = `<my-el-with-styles></my-el-with-styles>`
  316. const el = container.childNodes[0] as VueElement
  317. const style = el.shadowRoot?.querySelector('style')!
  318. expect(style.textContent).toBe(`div { color: red; }`)
  319. })
  320. })
  321. describe('async', () => {
  322. test('should work', async () => {
  323. const loaderSpy = jest.fn()
  324. const E = defineCustomElement(
  325. defineAsyncComponent(() => {
  326. loaderSpy()
  327. return Promise.resolve({
  328. props: ['msg'],
  329. styles: [`div { color: red }`],
  330. render(this: any) {
  331. return h('div', null, this.msg)
  332. }
  333. })
  334. })
  335. )
  336. customElements.define('my-el-async', E)
  337. container.innerHTML =
  338. `<my-el-async msg="hello"></my-el-async>` +
  339. `<my-el-async msg="world"></my-el-async>`
  340. await new Promise(r => setTimeout(r))
  341. // loader should be called only once
  342. expect(loaderSpy).toHaveBeenCalledTimes(1)
  343. const e1 = container.childNodes[0] as VueElement
  344. const e2 = container.childNodes[1] as VueElement
  345. // should inject styles
  346. expect(e1.shadowRoot!.innerHTML).toBe(
  347. `<style>div { color: red }</style><div>hello</div>`
  348. )
  349. expect(e2.shadowRoot!.innerHTML).toBe(
  350. `<style>div { color: red }</style><div>world</div>`
  351. )
  352. // attr
  353. e1.setAttribute('msg', 'attr')
  354. await nextTick()
  355. expect((e1 as any).msg).toBe('attr')
  356. expect(e1.shadowRoot!.innerHTML).toBe(
  357. `<style>div { color: red }</style><div>attr</div>`
  358. )
  359. // props
  360. expect(`msg` in e1).toBe(true)
  361. ;(e1 as any).msg = 'prop'
  362. expect(e1.getAttribute('msg')).toBe('prop')
  363. expect(e1.shadowRoot!.innerHTML).toBe(
  364. `<style>div { color: red }</style><div>prop</div>`
  365. )
  366. })
  367. test('set DOM property before resolve', async () => {
  368. const E = defineCustomElement(
  369. defineAsyncComponent(() => {
  370. return Promise.resolve({
  371. props: ['msg'],
  372. setup(props) {
  373. expect(typeof props.msg).toBe('string')
  374. },
  375. render(this: any) {
  376. return h('div', this.msg)
  377. }
  378. })
  379. })
  380. )
  381. customElements.define('my-el-async-2', E)
  382. const e1 = new E()
  383. // set property before connect
  384. e1.msg = 'hello'
  385. const e2 = new E()
  386. container.appendChild(e1)
  387. container.appendChild(e2)
  388. // set property after connect but before resolve
  389. e2.msg = 'world'
  390. await new Promise(r => setTimeout(r))
  391. expect(e1.shadowRoot!.innerHTML).toBe(`<div>hello</div>`)
  392. expect(e2.shadowRoot!.innerHTML).toBe(`<div>world</div>`)
  393. e1.msg = 'world'
  394. expect(e1.shadowRoot!.innerHTML).toBe(`<div>world</div>`)
  395. e2.msg = 'hello'
  396. expect(e2.shadowRoot!.innerHTML).toBe(`<div>hello</div>`)
  397. })
  398. test('Number prop casting before resolve', async () => {
  399. const E = defineCustomElement(
  400. defineAsyncComponent(() => {
  401. return Promise.resolve({
  402. props: { n: Number },
  403. setup(props) {
  404. expect(props.n).toBe(20)
  405. },
  406. render(this: any) {
  407. return h('div', this.n + ',' + typeof this.n)
  408. }
  409. })
  410. })
  411. )
  412. customElements.define('my-el-async-3', E)
  413. container.innerHTML = `<my-el-async-3 n="2e1"></my-el-async-3>`
  414. await new Promise(r => setTimeout(r))
  415. const e = container.childNodes[0] as VueElement
  416. expect(e.shadowRoot!.innerHTML).toBe(`<div>20,number</div>`)
  417. })
  418. test('with slots', async () => {
  419. const E = defineCustomElement(
  420. defineAsyncComponent(() => {
  421. return Promise.resolve({
  422. render(this: any) {
  423. return [
  424. h('div', null, [
  425. renderSlot(this.$slots, 'default', undefined, () => [
  426. h('div', 'fallback')
  427. ])
  428. ]),
  429. h('div', null, renderSlot(this.$slots, 'named'))
  430. ]
  431. }
  432. })
  433. })
  434. )
  435. customElements.define('my-el-async-slots', E)
  436. container.innerHTML = `<my-el-async-slots><span>hi</span></my-el-async-slots>`
  437. await new Promise(r => setTimeout(r))
  438. const e = container.childNodes[0] as VueElement
  439. expect(e.shadowRoot!.innerHTML).toBe(
  440. `<div><slot><div>fallback</div></slot></div><div><slot name="named"></slot></div>`
  441. )
  442. })
  443. })
  444. })