apiSetupHelpers.spec.ts 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. import {
  2. defineComponent,
  3. h,
  4. nodeOps,
  5. render,
  6. SetupContext
  7. } from '@vue/runtime-test'
  8. import {
  9. defineEmits,
  10. defineProps,
  11. defineExpose,
  12. withDefaults,
  13. useAttrs,
  14. useSlots,
  15. mergeDefaults
  16. } from '../src/apiSetupHelpers'
  17. describe('SFC <script setup> helpers', () => {
  18. test('should warn runtime usage', () => {
  19. defineProps()
  20. expect(`defineProps() is a compiler-hint`).toHaveBeenWarned()
  21. defineEmits()
  22. expect(`defineEmits() is a compiler-hint`).toHaveBeenWarned()
  23. defineExpose()
  24. expect(`defineExpose() is a compiler-hint`).toHaveBeenWarned()
  25. withDefaults({}, {})
  26. expect(`withDefaults() is a compiler-hint`).toHaveBeenWarned()
  27. })
  28. test('useSlots / useAttrs (no args)', () => {
  29. let slots: SetupContext['slots'] | undefined
  30. let attrs: SetupContext['attrs'] | undefined
  31. const Comp = {
  32. setup() {
  33. slots = useSlots()
  34. attrs = useAttrs()
  35. return () => {}
  36. }
  37. }
  38. const passedAttrs = { id: 'foo' }
  39. const passedSlots = {
  40. default: () => {},
  41. x: () => {}
  42. }
  43. render(h(Comp, passedAttrs, passedSlots), nodeOps.createElement('div'))
  44. expect(typeof slots!.default).toBe('function')
  45. expect(typeof slots!.x).toBe('function')
  46. expect(attrs).toMatchObject(passedAttrs)
  47. })
  48. test('useSlots / useAttrs (with args)', () => {
  49. let slots: SetupContext['slots'] | undefined
  50. let attrs: SetupContext['attrs'] | undefined
  51. let ctx: SetupContext | undefined
  52. const Comp = defineComponent({
  53. setup(_, _ctx) {
  54. slots = useSlots()
  55. attrs = useAttrs()
  56. ctx = _ctx
  57. return () => {}
  58. }
  59. })
  60. render(h(Comp), nodeOps.createElement('div'))
  61. expect(slots).toBe(ctx!.slots)
  62. expect(attrs).toBe(ctx!.attrs)
  63. })
  64. test('mergeDefaults', () => {
  65. const merged = mergeDefaults(
  66. {
  67. foo: null,
  68. bar: { type: String, required: false }
  69. },
  70. {
  71. foo: 1,
  72. bar: 'baz'
  73. }
  74. )
  75. expect(merged).toMatchObject({
  76. foo: { default: 1 },
  77. bar: { type: String, required: false, default: 'baz' }
  78. })
  79. mergeDefaults({}, { foo: 1 })
  80. expect(
  81. `props default key "foo" has no corresponding declaration`
  82. ).toHaveBeenWarned()
  83. })
  84. })