vue3-yuanma/packages/runtime-core/__tests__/apiCreateComponent.spec.tsx

110 lines
2.3 KiB
TypeScript
Raw Normal View History

import { createComponent } from '../src/component'
2019-08-22 05:10:37 +08:00
import { ref } from '@vue/reactivity'
2019-06-01 00:47:05 +08:00
import { PropType } from '../src/componentProps'
// mock React just for TSX testing purposes
const React = {
createElement: () => {}
}
test('createComponent type inference', () => {
const MyComponent = createComponent({
props: {
a: Number,
2019-06-01 00:47:05 +08:00
// required should make property non-void
b: {
2019-06-01 00:47:05 +08:00
type: String,
required: true
},
// default value should infer type and make it non-void
bb: {
default: 'hello'
},
// explicit type casting
cc: (Array as any) as PropType<string[]>,
// required + type casting
dd: {
type: (Array as any) as PropType<string[]>,
required: true
}
2019-06-01 00:47:05 +08:00
} as const, // required to narrow for conditional check
setup(props) {
2019-06-01 00:47:05 +08:00
props.a && props.a * 2
props.b.slice()
2019-06-01 00:47:05 +08:00
props.bb.slice()
props.cc && props.cc.push('hoo')
props.dd.push('dd')
return {
2019-08-22 05:10:37 +08:00
c: ref(1),
d: {
2019-08-22 05:10:37 +08:00
e: ref('hi')
}
}
},
render() {
const props = this.$props
2019-06-01 00:47:05 +08:00
props.a && props.a * 2
props.b.slice()
2019-06-01 00:47:05 +08:00
props.bb.slice()
props.cc && props.cc.push('hoo')
props.dd.push('dd')
this.a && this.a * 2
this.b.slice()
2019-06-01 00:47:05 +08:00
this.bb.slice()
this.c * 2
this.d.e.slice()
2019-06-01 00:47:05 +08:00
this.cc && this.cc.push('hoo')
this.dd.push('dd')
}
})
// test TSX props inference
;(<MyComponent a={1} b="foo" dd={['foo']}/>)
})
2019-06-01 00:47:05 +08:00
test('type inference w/ optional props declaration', () => {
const Comp = createComponent({
setup(props: { msg: string }) {
props.msg
2019-06-01 00:47:05 +08:00
return {
a: 1
}
},
render() {
this.$props.msg
this.$data.a * 2
2019-06-19 16:43:34 +08:00
this.msg
2019-06-01 00:47:05 +08:00
this.a * 2
}
})
;(<Comp msg="hello"/>)
2019-06-01 00:47:05 +08:00
})
test('type inference w/ direct setup function', () => {
const Comp = createComponent((props: { msg: string }) => {
return () => <div>{props.msg}</div>
})
;(<Comp msg="hello"/>)
})
test('type inference w/ array props declaration', () => {
const Comp = createComponent({
props: ['a', 'b'],
setup(props) {
props.a
props.b
return {
c: 1
}
},
render() {
this.$props.a
this.$props.b
this.$data.c
this.a
this.b
this.c
}
})
;(<Comp a={1} b={2}/>)
})