customElement.spec.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  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. foo: Number,
  122. bar: Boolean,
  123. baz: String
  124. },
  125. render() {
  126. return [
  127. this.foo,
  128. typeof this.foo,
  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="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', '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. })
  192. describe('emits', () => {
  193. const E = defineCustomElement({
  194. setup(_, { emit }) {
  195. emit('created')
  196. return () =>
  197. h('div', {
  198. onClick: () => emit('my-click', 1)
  199. })
  200. }
  201. })
  202. customElements.define('my-el-emits', E)
  203. test('emit on connect', () => {
  204. const e = new E()
  205. const spy = jest.fn()
  206. e.addEventListener('created', spy)
  207. container.appendChild(e)
  208. expect(spy).toHaveBeenCalled()
  209. })
  210. test('emit on interaction', () => {
  211. container.innerHTML = `<my-el-emits></my-el-emits>`
  212. const e = container.childNodes[0] as VueElement
  213. const spy = jest.fn()
  214. e.addEventListener('my-click', spy)
  215. e.shadowRoot!.childNodes[0].dispatchEvent(new CustomEvent('click'))
  216. expect(spy).toHaveBeenCalled()
  217. expect(spy.mock.calls[0][0]).toMatchObject({
  218. detail: [1]
  219. })
  220. })
  221. })
  222. describe('slots', () => {
  223. const E = defineCustomElement({
  224. render() {
  225. return [
  226. h('div', null, [
  227. renderSlot(this.$slots, 'default', undefined, () => [
  228. h('div', 'fallback')
  229. ])
  230. ]),
  231. h('div', null, renderSlot(this.$slots, 'named'))
  232. ]
  233. }
  234. })
  235. customElements.define('my-el-slots', E)
  236. test('default slot', () => {
  237. container.innerHTML = `<my-el-slots><span>hi</span></my-el-slots>`
  238. const e = container.childNodes[0] as VueElement
  239. // native slots allocation does not affect innerHTML, so we just
  240. // verify that we've rendered the correct native slots here...
  241. expect(e.shadowRoot!.innerHTML).toBe(
  242. `<div><slot><div>fallback</div></slot></div><div><slot name="named"></slot></div>`
  243. )
  244. })
  245. })
  246. describe('provide/inject', () => {
  247. const Consumer = defineCustomElement({
  248. setup() {
  249. const foo = inject<Ref>('foo')!
  250. return () => h('div', foo.value)
  251. }
  252. })
  253. customElements.define('my-consumer', Consumer)
  254. test('over nested usage', async () => {
  255. const foo = ref('injected!')
  256. const Provider = defineCustomElement({
  257. provide: {
  258. foo
  259. },
  260. render() {
  261. return h('my-consumer')
  262. }
  263. })
  264. customElements.define('my-provider', Provider)
  265. container.innerHTML = `<my-provider><my-provider>`
  266. const provider = container.childNodes[0] as VueElement
  267. const consumer = provider.shadowRoot!.childNodes[0] as VueElement
  268. expect(consumer.shadowRoot!.innerHTML).toBe(`<div>injected!</div>`)
  269. foo.value = 'changed!'
  270. await nextTick()
  271. expect(consumer.shadowRoot!.innerHTML).toBe(`<div>changed!</div>`)
  272. })
  273. test('over slot composition', async () => {
  274. const foo = ref('injected!')
  275. const Provider = defineCustomElement({
  276. provide: {
  277. foo
  278. },
  279. render() {
  280. return renderSlot(this.$slots, 'default')
  281. }
  282. })
  283. customElements.define('my-provider-2', Provider)
  284. container.innerHTML = `<my-provider-2><my-consumer></my-consumer><my-provider-2>`
  285. const provider = container.childNodes[0]
  286. const consumer = provider.childNodes[0] as VueElement
  287. expect(consumer.shadowRoot!.innerHTML).toBe(`<div>injected!</div>`)
  288. foo.value = 'changed!'
  289. await nextTick()
  290. expect(consumer.shadowRoot!.innerHTML).toBe(`<div>changed!</div>`)
  291. })
  292. })
  293. describe('styles', () => {
  294. test('should attach styles to shadow dom', () => {
  295. const Foo = defineCustomElement({
  296. styles: [`div { color: red; }`],
  297. render() {
  298. return h('div', 'hello')
  299. }
  300. })
  301. customElements.define('my-el-with-styles', Foo)
  302. container.innerHTML = `<my-el-with-styles></my-el-with-styles>`
  303. const el = container.childNodes[0] as VueElement
  304. const style = el.shadowRoot?.querySelector('style')!
  305. expect(style.textContent).toBe(`div { color: red; }`)
  306. })
  307. })
  308. describe('async', () => {
  309. test('should work', async () => {
  310. const loaderSpy = jest.fn()
  311. const E = defineCustomElement(
  312. defineAsyncComponent(() => {
  313. loaderSpy()
  314. return Promise.resolve({
  315. props: ['msg'],
  316. styles: [`div { color: red }`],
  317. render(this: any) {
  318. return h('div', null, this.msg)
  319. }
  320. })
  321. })
  322. )
  323. customElements.define('my-el-async', E)
  324. container.innerHTML =
  325. `<my-el-async msg="hello"></my-el-async>` +
  326. `<my-el-async msg="world"></my-el-async>`
  327. await new Promise(r => setTimeout(r))
  328. // loader should be called only once
  329. expect(loaderSpy).toHaveBeenCalledTimes(1)
  330. const e1 = container.childNodes[0] as VueElement
  331. const e2 = container.childNodes[1] as VueElement
  332. // should inject styles
  333. expect(e1.shadowRoot!.innerHTML).toBe(
  334. `<style>div { color: red }</style><div>hello</div>`
  335. )
  336. expect(e2.shadowRoot!.innerHTML).toBe(
  337. `<style>div { color: red }</style><div>world</div>`
  338. )
  339. // attr
  340. e1.setAttribute('msg', 'attr')
  341. await nextTick()
  342. expect((e1 as any).msg).toBe('attr')
  343. expect(e1.shadowRoot!.innerHTML).toBe(
  344. `<style>div { color: red }</style><div>attr</div>`
  345. )
  346. // props
  347. expect(`msg` in e1).toBe(true)
  348. ;(e1 as any).msg = 'prop'
  349. expect(e1.getAttribute('msg')).toBe('prop')
  350. expect(e1.shadowRoot!.innerHTML).toBe(
  351. `<style>div { color: red }</style><div>prop</div>`
  352. )
  353. })
  354. test('set DOM property before resolve', async () => {
  355. const E = defineCustomElement(
  356. defineAsyncComponent(() => {
  357. return Promise.resolve({
  358. props: ['msg'],
  359. setup(props) {
  360. expect(typeof props.msg).toBe('string')
  361. },
  362. render(this: any) {
  363. return h('div', this.msg)
  364. }
  365. })
  366. })
  367. )
  368. customElements.define('my-el-async-2', E)
  369. const e1 = new E()
  370. // set property before connect
  371. e1.msg = 'hello'
  372. const e2 = new E()
  373. container.appendChild(e1)
  374. container.appendChild(e2)
  375. // set property after connect but before resolve
  376. e2.msg = 'world'
  377. await new Promise(r => setTimeout(r))
  378. expect(e1.shadowRoot!.innerHTML).toBe(`<div>hello</div>`)
  379. expect(e2.shadowRoot!.innerHTML).toBe(`<div>world</div>`)
  380. e1.msg = 'world'
  381. expect(e1.shadowRoot!.innerHTML).toBe(`<div>world</div>`)
  382. e2.msg = 'hello'
  383. expect(e2.shadowRoot!.innerHTML).toBe(`<div>hello</div>`)
  384. })
  385. test('Number prop casting before resolve', async () => {
  386. const E = defineCustomElement(
  387. defineAsyncComponent(() => {
  388. return Promise.resolve({
  389. props: { n: Number },
  390. setup(props) {
  391. expect(props.n).toBe(20)
  392. },
  393. render(this: any) {
  394. return h('div', this.n + ',' + typeof this.n)
  395. }
  396. })
  397. })
  398. )
  399. customElements.define('my-el-async-3', E)
  400. container.innerHTML = `<my-el-async-3 n="2e1"></my-el-async-3>`
  401. await new Promise(r => setTimeout(r))
  402. const e = container.childNodes[0] as VueElement
  403. expect(e.shadowRoot!.innerHTML).toBe(`<div>20,number</div>`)
  404. })
  405. })
  406. })