apiExpose.spec.ts 2.5 KB

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