componentCurrentInstance.spec.ts 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import { h, nodeOps, render, useInstanceOption } from '@vue/runtime-test'
  2. describe('useInstanceOption', () => {
  3. test(`'ce' key`, () => {
  4. let hasInstance: boolean | undefined
  5. let ce: any
  6. const Comp = {
  7. setup() {
  8. const option = useInstanceOption('ce', true)
  9. hasInstance = option.hasInstance
  10. ce = option.value
  11. return () => null
  12. },
  13. }
  14. render(h(Comp), nodeOps.createElement('div'))
  15. expect(hasInstance).toBe(true)
  16. // custom element definition is not supported in test renderer, so check to access it is enough
  17. expect(ce).toBeUndefined()
  18. })
  19. test(`'type' key`, () => {
  20. let hasInstance: boolean | undefined
  21. let type: any
  22. const Comp = {
  23. __i18n: { locale: 'en' }, // inject by custom blocks
  24. setup() {
  25. const option = useInstanceOption('type', true)
  26. hasInstance = option.hasInstance
  27. type = option.value
  28. return () => null
  29. },
  30. mounted() {},
  31. }
  32. render(h(Comp), nodeOps.createElement('div'))
  33. expect(hasInstance).toBe(true)
  34. expect('setup' in type).toBe(true)
  35. expect('mounted' in type).toBe(true)
  36. expect(type.__i18n).toEqual({ locale: 'en' })
  37. })
  38. test(`'uid' key`, () => {
  39. let hasInstance: boolean | undefined
  40. let uid: any
  41. const Comp = {
  42. setup() {
  43. const option = useInstanceOption('uid', true)
  44. hasInstance = option.hasInstance
  45. uid = option.value
  46. return () => null
  47. },
  48. }
  49. render(h(Comp), nodeOps.createElement('div'))
  50. expect(hasInstance).toBe(true)
  51. expect(typeof uid).toBe('number')
  52. })
  53. test('not allowed key', () => {
  54. let hasInstance: boolean | undefined
  55. let value: any
  56. const Comp = {
  57. setup() {
  58. const option = useInstanceOption('foo' as any, true)
  59. hasInstance = option.hasInstance
  60. value = option.value
  61. return () => null
  62. },
  63. }
  64. render(h(Comp), nodeOps.createElement('div'))
  65. expect(hasInstance).toBe(true)
  66. expect(value).toBeUndefined()
  67. expect(
  68. `useInstanceOption only accepts 'ce', 'type', 'uid' as key, got 'foo'.`,
  69. ).toHaveBeenWarned()
  70. })
  71. test('not active instance', () => {
  72. const { hasInstance, value } = useInstanceOption('type')
  73. expect(hasInstance).toBe(false)
  74. expect(value).toBeUndefined()
  75. expect(
  76. 'useInstanceOption called without an active component instance.',
  77. ).toHaveBeenWarned()
  78. })
  79. })