customElement.spec.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  1. import {
  2. defineAsyncComponent,
  3. defineCustomElement,
  4. h,
  5. inject,
  6. nextTick,
  7. Ref,
  8. ref,
  9. renderSlot,
  10. VueElement
  11. } from '../src'
  12. import { parseNumber } from '../src/apiCustomElement'
  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. })
  69. describe('props', () => {
  70. const E = defineCustomElement({
  71. props: ['foo', 'bar', 'bazQux'],
  72. render() {
  73. return [
  74. h('div', null, this.foo),
  75. h('div', null, this.bazQux || (this.bar && this.bar.x))
  76. ]
  77. }
  78. })
  79. customElements.define('my-el-props', E)
  80. test('props via attribute', async () => {
  81. // bazQux should map to `baz-qux` attribute
  82. container.innerHTML = `<my-el-props foo="hello" baz-qux="bye"></my-el-props>`
  83. const e = container.childNodes[0] as VueElement
  84. expect(e.shadowRoot!.innerHTML).toBe('<div>hello</div><div>bye</div>')
  85. // change attr
  86. e.setAttribute('foo', 'changed')
  87. await nextTick()
  88. expect(e.shadowRoot!.innerHTML).toBe('<div>changed</div><div>bye</div>')
  89. e.setAttribute('baz-qux', 'changed')
  90. await nextTick()
  91. expect(e.shadowRoot!.innerHTML).toBe(
  92. '<div>changed</div><div>changed</div>'
  93. )
  94. })
  95. test('props via properties', async () => {
  96. const e = new E()
  97. e.foo = 'one'
  98. e.bar = { x: 'two' }
  99. container.appendChild(e)
  100. expect(e.shadowRoot!.innerHTML).toBe('<div>one</div><div>two</div>')
  101. // reflect
  102. // should reflect primitive value
  103. expect(e.getAttribute('foo')).toBe('one')
  104. // should not reflect rich data
  105. expect(e.hasAttribute('bar')).toBe(false)
  106. e.foo = 'three'
  107. await nextTick()
  108. expect(e.shadowRoot!.innerHTML).toBe('<div>three</div><div>two</div>')
  109. expect(e.getAttribute('foo')).toBe('three')
  110. e.foo = null
  111. await nextTick()
  112. expect(e.shadowRoot!.innerHTML).toBe('<div></div><div>two</div>')
  113. expect(e.hasAttribute('foo')).toBe(false)
  114. e.bazQux = 'four'
  115. await nextTick()
  116. expect(e.shadowRoot!.innerHTML).toBe('<div></div><div>four</div>')
  117. expect(e.getAttribute('baz-qux')).toBe('four')
  118. })
  119. test('attribute -> prop type casting', async () => {
  120. const E = defineCustomElement({
  121. props: {
  122. foo: Number,
  123. bar: Boolean
  124. },
  125. render() {
  126. return [this.foo, typeof this.foo, this.bar, typeof this.bar].join(
  127. ' '
  128. )
  129. }
  130. })
  131. customElements.define('my-el-props-cast', E)
  132. container.innerHTML = `<my-el-props-cast foo="1"></my-el-props-cast>`
  133. const e = container.childNodes[0] as VueElement
  134. expect(e.shadowRoot!.innerHTML).toBe(`1 number false boolean`)
  135. e.setAttribute('bar', '')
  136. await nextTick()
  137. expect(e.shadowRoot!.innerHTML).toBe(`1 number true boolean`)
  138. e.setAttribute('foo', '2e1')
  139. await nextTick()
  140. expect(e.shadowRoot!.innerHTML).toBe(`20 number true boolean`)
  141. })
  142. test('handling properties set before upgrading', () => {
  143. const E = defineCustomElement({
  144. props: ['foo'],
  145. render() {
  146. return `foo: ${this.foo}`
  147. }
  148. })
  149. const el = document.createElement('my-el-upgrade') as any
  150. el.foo = 'hello'
  151. container.appendChild(el)
  152. customElements.define('my-el-upgrade', E)
  153. expect(el.shadowRoot.innerHTML).toBe(`foo: hello`)
  154. })
  155. })
  156. describe('emits', () => {
  157. const E = defineCustomElement({
  158. setup(_, { emit }) {
  159. emit('created')
  160. return () =>
  161. h('div', {
  162. onClick: () => emit('my-click', 1)
  163. })
  164. }
  165. })
  166. customElements.define('my-el-emits', E)
  167. test('emit on connect', () => {
  168. const e = new E()
  169. const spy = jest.fn()
  170. e.addEventListener('created', spy)
  171. container.appendChild(e)
  172. expect(spy).toHaveBeenCalled()
  173. })
  174. test('emit on interaction', () => {
  175. container.innerHTML = `<my-el-emits></my-el-emits>`
  176. const e = container.childNodes[0] as VueElement
  177. const spy = jest.fn()
  178. e.addEventListener('my-click', spy)
  179. e.shadowRoot!.childNodes[0].dispatchEvent(new CustomEvent('click'))
  180. expect(spy).toHaveBeenCalled()
  181. expect(spy.mock.calls[0][0]).toMatchObject({
  182. detail: [1]
  183. })
  184. })
  185. })
  186. describe('slots', () => {
  187. const E = defineCustomElement({
  188. render() {
  189. return [
  190. h('div', null, [
  191. renderSlot(this.$slots, 'default', undefined, () => [
  192. h('div', 'fallback')
  193. ])
  194. ]),
  195. h('div', null, renderSlot(this.$slots, 'named'))
  196. ]
  197. }
  198. })
  199. customElements.define('my-el-slots', E)
  200. test('default slot', () => {
  201. container.innerHTML = `<my-el-slots><span>hi</span></my-el-slots>`
  202. const e = container.childNodes[0] as VueElement
  203. // native slots allocation does not affect innerHTML, so we just
  204. // verify that we've rendered the correct native slots here...
  205. expect(e.shadowRoot!.innerHTML).toBe(
  206. `<div><slot><div>fallback</div></slot></div><div><slot name="named"></slot></div>`
  207. )
  208. })
  209. })
  210. describe('provide/inject', () => {
  211. const Consumer = defineCustomElement({
  212. setup() {
  213. const foo = inject<Ref>('foo')!
  214. return () => h('div', foo.value)
  215. }
  216. })
  217. customElements.define('my-consumer', Consumer)
  218. test('over nested usage', async () => {
  219. const foo = ref('injected!')
  220. const Provider = defineCustomElement({
  221. provide: {
  222. foo
  223. },
  224. render() {
  225. return h('my-consumer')
  226. }
  227. })
  228. customElements.define('my-provider', Provider)
  229. container.innerHTML = `<my-provider><my-provider>`
  230. const provider = container.childNodes[0] as VueElement
  231. const consumer = provider.shadowRoot!.childNodes[0] as VueElement
  232. expect(consumer.shadowRoot!.innerHTML).toBe(`<div>injected!</div>`)
  233. foo.value = 'changed!'
  234. await nextTick()
  235. expect(consumer.shadowRoot!.innerHTML).toBe(`<div>changed!</div>`)
  236. })
  237. test('over slot composition', async () => {
  238. const foo = ref('injected!')
  239. const Provider = defineCustomElement({
  240. provide: {
  241. foo
  242. },
  243. render() {
  244. return renderSlot(this.$slots, 'default')
  245. }
  246. })
  247. customElements.define('my-provider-2', Provider)
  248. container.innerHTML = `<my-provider-2><my-consumer></my-consumer><my-provider-2>`
  249. const provider = container.childNodes[0]
  250. const consumer = provider.childNodes[0] as VueElement
  251. expect(consumer.shadowRoot!.innerHTML).toBe(`<div>injected!</div>`)
  252. foo.value = 'changed!'
  253. await nextTick()
  254. expect(consumer.shadowRoot!.innerHTML).toBe(`<div>changed!</div>`)
  255. })
  256. })
  257. describe('styles', () => {
  258. test('should attach styles to shadow dom', () => {
  259. const Foo = defineCustomElement({
  260. styles: [`div { color: red; }`],
  261. render() {
  262. return h('div', 'hello')
  263. }
  264. })
  265. customElements.define('my-el-with-styles', Foo)
  266. container.innerHTML = `<my-el-with-styles></my-el-with-styles>`
  267. const el = container.childNodes[0] as VueElement
  268. const style = el.shadowRoot?.querySelector('style')!
  269. expect(style.textContent).toBe(`div { color: red; }`)
  270. })
  271. })
  272. describe('async', () => {
  273. test('should work', async () => {
  274. const loaderSpy = jest.fn()
  275. const E = defineCustomElement(
  276. defineAsyncComponent(() => {
  277. loaderSpy()
  278. return Promise.resolve({
  279. props: ['msg'],
  280. styles: [`div { color: red }`],
  281. render(this: any) {
  282. return h('div', null, this.msg)
  283. }
  284. })
  285. })
  286. )
  287. customElements.define('my-el-async', E)
  288. container.innerHTML =
  289. `<my-el-async msg="hello"></my-el-async>` +
  290. `<my-el-async msg="world"></my-el-async>`
  291. await new Promise(r => setTimeout(r))
  292. // loader should be called only once
  293. expect(loaderSpy).toHaveBeenCalledTimes(1)
  294. const e1 = container.childNodes[0] as VueElement
  295. const e2 = container.childNodes[1] as VueElement
  296. // should inject styles
  297. expect(e1.shadowRoot!.innerHTML).toBe(
  298. `<div>hello</div><style>div { color: red }</style>`
  299. )
  300. expect(e2.shadowRoot!.innerHTML).toBe(
  301. `<div>world</div><style>div { color: red }</style>`
  302. )
  303. // attr
  304. e1.setAttribute('msg', 'attr')
  305. await nextTick()
  306. expect((e1 as any).msg).toBe('attr')
  307. expect(e1.shadowRoot!.innerHTML).toBe(
  308. `<div>attr</div><style>div { color: red }</style>`
  309. )
  310. // props
  311. expect(`msg` in e1).toBe(true)
  312. ;(e1 as any).msg = 'prop'
  313. expect(e1.getAttribute('msg')).toBe('prop')
  314. expect(e1.shadowRoot!.innerHTML).toBe(
  315. `<div>prop</div><style>div { color: red }</style>`
  316. )
  317. })
  318. test('set DOM property before resolve', async () => {
  319. const E = defineCustomElement(
  320. defineAsyncComponent(() => {
  321. return Promise.resolve({
  322. props: ['msg'],
  323. render(this: any) {
  324. return h('div', this.msg)
  325. }
  326. })
  327. })
  328. )
  329. customElements.define('my-el-async-2', E)
  330. const e1 = new E()
  331. // set property before connect
  332. e1.msg = 'hello'
  333. const e2 = new E()
  334. container.appendChild(e1)
  335. container.appendChild(e2)
  336. // set property after connect but before resolve
  337. e2.msg = 'world'
  338. await new Promise(r => setTimeout(r))
  339. expect(e1.shadowRoot!.innerHTML).toBe(`<div>hello</div>`)
  340. expect(e2.shadowRoot!.innerHTML).toBe(`<div>world</div>`)
  341. e1.msg = 'world'
  342. expect(e1.shadowRoot!.innerHTML).toBe(`<div>world</div>`)
  343. e2.msg = 'hello'
  344. expect(e2.shadowRoot!.innerHTML).toBe(`<div>hello</div>`)
  345. })
  346. })
  347. })
  348. describe('parseNumber', () => {
  349. it('handles strings', () => {
  350. expect(parseNumber('')).toBe('')
  351. expect(parseNumber(null)).toBe('')
  352. expect(parseNumber('Something else')).toBe('Something else')
  353. })
  354. it('numbers', () => {
  355. expect(parseNumber('0')).toBe(0)
  356. expect(parseNumber('1')).toBe(1)
  357. expect(parseNumber('1.1')).toBe(1.1)
  358. expect(parseNumber('123e-1')).toBe(12.3)
  359. expect(parseNumber('Infinity')).toBe(Infinity)
  360. })
  361. it('NaN', () => {
  362. expect(parseNumber('NaN')).toBeNaN()
  363. expect(parseNumber('nan')).not.toBeNaN()
  364. })
  365. // all of these are handled by Number
  366. it('string non decimal bases', () => {
  367. expect(parseNumber('0b0')).toBe(0)
  368. expect(parseNumber('0b1')).toBe(1)
  369. expect(parseNumber('0o3')).toBe(3)
  370. expect(parseNumber('0o0')).toBe(0)
  371. expect(parseNumber('0x0')).toBe(0)
  372. expect(parseNumber('0xf')).toBe(15)
  373. })
  374. })