apiCreateComponent.spec.tsx 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  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() {
  43. const props = this.$props
  44. props.a && props.a * 2
  45. props.b.slice()
  46. props.bb.slice()
  47. props.cc && props.cc.push('hoo')
  48. props.dd.push('dd')
  49. this.a && this.a * 2
  50. this.b.slice()
  51. this.bb.slice()
  52. this.c * 2
  53. this.d.e.slice()
  54. this.cc && this.cc.push('hoo')
  55. this.dd.push('dd')
  56. }
  57. })
  58. // test TSX props inference
  59. ;(<MyComponent a={1} b="foo" dd={['foo']}/>)
  60. })
  61. test('type inference w/ optional props declaration', () => {
  62. const Comp = createComponent({
  63. setup(props: { msg: string }) {
  64. props.msg
  65. return {
  66. a: 1
  67. }
  68. },
  69. render() {
  70. this.$props.msg
  71. this.$data.a * 2
  72. this.msg
  73. this.a * 2
  74. }
  75. })
  76. ;(<Comp msg="hello"/>)
  77. })
  78. test('type inference w/ direct setup function', () => {
  79. const Comp = createComponent((props: { msg: string }) => {
  80. return () => <div>{props.msg}</div>
  81. })
  82. ;(<Comp msg="hello"/>)
  83. })
  84. test('type inference w/ array props declaration', () => {
  85. const Comp = createComponent({
  86. props: ['a', 'b'],
  87. setup(props) {
  88. props.a
  89. props.b
  90. return {
  91. c: 1
  92. }
  93. },
  94. render() {
  95. this.$props.a
  96. this.$props.b
  97. this.$data.c
  98. this.a
  99. this.b
  100. this.c
  101. }
  102. })
  103. ;(<Comp a={1} b={2}/>)
  104. })