apiExpose.spec.ts 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. import { ref, shallowRef } from '@vue/reactivity'
  2. import { type VaporComponentInstance, createComponent } from '../src/component'
  3. import { setRef } from '../src/dom/templateRef'
  4. import { makeRender } from './_utils'
  5. import { currentInstance } from '@vue/runtime-dom'
  6. import { defineVaporComponent } from '../src/apiDefineComponent'
  7. const define = makeRender()
  8. describe('api: expose', () => {
  9. test.todo('via setup context + template ref', () => {
  10. const Child = defineVaporComponent({
  11. setup(_, { expose }) {
  12. expose({
  13. foo: 1,
  14. bar: ref(2),
  15. })
  16. return []
  17. },
  18. })
  19. const childRef = ref()
  20. define({
  21. render: () => {
  22. const n0 = createComponent(Child)
  23. return n0
  24. },
  25. }).render()
  26. expect(childRef.value).toBeTruthy()
  27. expect(childRef.value.foo).toBe(1)
  28. expect(childRef.value.bar).toBe(2)
  29. expect(childRef.value.baz).toBeUndefined()
  30. })
  31. test.todo('via setup context + template ref (expose empty)', () => {
  32. let childInstance: VaporComponentInstance | null = null
  33. const Child = defineVaporComponent({
  34. setup(_) {
  35. childInstance = currentInstance as VaporComponentInstance
  36. return []
  37. },
  38. })
  39. const childRef = shallowRef()
  40. define({
  41. render: () => {
  42. const n0 = createComponent(Child)
  43. setRef(n0, childRef)
  44. return n0
  45. },
  46. }).render()
  47. expect(childInstance!.exposed).toBeUndefined()
  48. expect(childRef.value).toBe(childInstance!)
  49. })
  50. test('with mount', () => {
  51. const { app, host } = define({
  52. setup(_, { expose }) {
  53. expose({
  54. foo: 1,
  55. })
  56. return []
  57. },
  58. }).create()
  59. const exposed = app.mount(host) as any
  60. expect(exposed.foo).toBe(1)
  61. expect(exposed.bar).toBe(undefined)
  62. })
  63. test('warning for ref', () => {
  64. define({
  65. setup(_, { expose }) {
  66. expose(ref(1))
  67. return []
  68. },
  69. }).render()
  70. expect(
  71. 'expose() should be passed a plain object, received ref',
  72. ).toHaveBeenWarned()
  73. })
  74. test('warning for array', () => {
  75. define({
  76. setup(_, { expose }) {
  77. expose(['focus'])
  78. return []
  79. },
  80. }).render()
  81. expect(
  82. 'expose() should be passed a plain object, received array',
  83. ).toHaveBeenWarned()
  84. })
  85. test('warning for function', () => {
  86. define({
  87. setup(_, { expose }) {
  88. expose(() => null)
  89. return []
  90. },
  91. }).render()
  92. expect(
  93. 'expose() should be passed a plain object, received function',
  94. ).toHaveBeenWarned()
  95. })
  96. })