createComponent.spec.tsx 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. import { createComponent } from '../src/component'
  2. import { ref } from '@vue/reactivity'
  3. import { PropType } from '../src/componentProps'
  4. // mock React just for TSX testing purposes
  5. const React = {
  6. createElement: () => {}
  7. }
  8. test('createComponent type inference', () => {
  9. const MyComponent = createComponent({
  10. props: {
  11. a: Number,
  12. // required should make property non-void
  13. b: {
  14. type: String,
  15. required: true
  16. },
  17. // default value should infer type and make it non-void
  18. bb: {
  19. default: 'hello'
  20. },
  21. // explicit type casting
  22. cc: (Array as any) as PropType<string[]>,
  23. // required + type casting
  24. dd: {
  25. type: (Array as any) as PropType<string[]>,
  26. required: true
  27. }
  28. } as const, // required to narrow for conditional check
  29. setup(props) {
  30. props.a && props.a * 2
  31. props.b.slice()
  32. props.bb.slice()
  33. props.cc && props.cc.push('hoo')
  34. props.dd.push('dd')
  35. return {
  36. c: ref(1),
  37. d: {
  38. e: ref('hi')
  39. }
  40. }
  41. },
  42. render(props) {
  43. props.a && props.a * 2
  44. props.b.slice()
  45. props.bb.slice()
  46. props.cc && props.cc.push('hoo')
  47. props.dd.push('dd')
  48. this.a && this.a * 2
  49. this.b.slice()
  50. this.bb.slice()
  51. this.c * 2
  52. this.d.e.slice()
  53. this.cc && this.cc.push('hoo')
  54. this.dd.push('dd')
  55. }
  56. })
  57. // test TSX props inference
  58. ;(<MyComponent a={1} b="foo" dd={['foo']}/>)
  59. })
  60. test('type inference w/ optional props declaration', () => {
  61. const Comp = createComponent({
  62. setup(props: { msg: string }) {
  63. props.msg
  64. return {
  65. a: 1
  66. }
  67. },
  68. render(ctx) {
  69. ctx.msg
  70. ctx.a * 2
  71. this.msg
  72. this.a * 2
  73. }
  74. })
  75. ;(<Comp msg="hello"/>)
  76. })
  77. test('type inference w/ direct setup function', () => {
  78. const Comp = createComponent((props: { msg: string }) => {
  79. return () => <div>{props.msg}</div>
  80. })
  81. ;(<Comp msg="hello"/>)
  82. })
  83. test('type inference w/ array props declaration', () => {
  84. const Comp = createComponent({
  85. props: ['a', 'b'],
  86. setup(props) {
  87. props.a
  88. props.b
  89. return {
  90. c: 1
  91. }
  92. },
  93. render(ctx) {
  94. ctx.a
  95. ctx.b
  96. ctx.c
  97. this.a
  98. this.b
  99. this.c
  100. }
  101. })
  102. ;(<Comp a={1} b={2}/>)
  103. })