apiSetupHelpers.spec.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. import { vi } from 'vitest'
  2. import {
  3. ComponentInternalInstance,
  4. createApp,
  5. defineComponent,
  6. getCurrentInstance,
  7. h,
  8. nodeOps,
  9. onMounted,
  10. render,
  11. serializeInner,
  12. SetupContext,
  13. Suspense,
  14. computed,
  15. ComputedRef,
  16. shallowReactive
  17. } from '@vue/runtime-test'
  18. import {
  19. defineEmits,
  20. defineProps,
  21. defineExpose,
  22. withDefaults,
  23. useAttrs,
  24. useSlots,
  25. mergeDefaults,
  26. withAsyncContext,
  27. createPropsRestProxy
  28. } from '../src/apiSetupHelpers'
  29. describe('SFC <script setup> helpers', () => {
  30. test('should warn runtime usage', () => {
  31. defineProps()
  32. expect(`defineProps() is a compiler-hint`).toHaveBeenWarned()
  33. defineEmits()
  34. expect(`defineEmits() is a compiler-hint`).toHaveBeenWarned()
  35. defineExpose()
  36. expect(`defineExpose() is a compiler-hint`).toHaveBeenWarned()
  37. withDefaults({}, {})
  38. expect(`withDefaults() is a compiler-hint`).toHaveBeenWarned()
  39. })
  40. test('useSlots / useAttrs (no args)', () => {
  41. let slots: SetupContext['slots'] | undefined
  42. let attrs: SetupContext['attrs'] | undefined
  43. const Comp = {
  44. setup() {
  45. slots = useSlots()
  46. attrs = useAttrs()
  47. return () => {}
  48. }
  49. }
  50. const passedAttrs = { id: 'foo' }
  51. const passedSlots = {
  52. default: () => {},
  53. x: () => {}
  54. }
  55. render(h(Comp, passedAttrs, passedSlots), nodeOps.createElement('div'))
  56. expect(typeof slots!.default).toBe('function')
  57. expect(typeof slots!.x).toBe('function')
  58. expect(attrs).toMatchObject(passedAttrs)
  59. })
  60. test('useSlots / useAttrs (with args)', () => {
  61. let slots: SetupContext['slots'] | undefined
  62. let attrs: SetupContext['attrs'] | undefined
  63. let ctx: SetupContext | undefined
  64. const Comp = defineComponent({
  65. setup(_, _ctx) {
  66. slots = useSlots()
  67. attrs = useAttrs()
  68. ctx = _ctx
  69. return () => {}
  70. }
  71. })
  72. render(h(Comp), nodeOps.createElement('div'))
  73. expect(slots).toBe(ctx!.slots)
  74. expect(attrs).toBe(ctx!.attrs)
  75. })
  76. describe('mergeDefaults', () => {
  77. test('object syntax', () => {
  78. const merged = mergeDefaults(
  79. {
  80. foo: null,
  81. bar: { type: String, required: false },
  82. baz: String
  83. },
  84. {
  85. foo: 1,
  86. bar: 'baz',
  87. baz: 'qux'
  88. }
  89. )
  90. expect(merged).toMatchObject({
  91. foo: { default: 1 },
  92. bar: { type: String, required: false, default: 'baz' },
  93. baz: { type: String, default: 'qux' }
  94. })
  95. })
  96. test('array syntax', () => {
  97. const merged = mergeDefaults(['foo', 'bar', 'baz'], {
  98. foo: 1,
  99. bar: 'baz',
  100. baz: 'qux'
  101. })
  102. expect(merged).toMatchObject({
  103. foo: { default: 1 },
  104. bar: { default: 'baz' },
  105. baz: { default: 'qux' }
  106. })
  107. })
  108. test('merging with skipFactory', () => {
  109. const fn = () => {}
  110. const merged = mergeDefaults(['foo', 'bar', 'baz'], {
  111. foo: fn,
  112. __skip_foo: true
  113. })
  114. expect(merged).toMatchObject({
  115. foo: { default: fn, skipFactory: true }
  116. })
  117. })
  118. test('should warn missing', () => {
  119. mergeDefaults({}, { foo: 1 })
  120. expect(
  121. `props default key "foo" has no corresponding declaration`
  122. ).toHaveBeenWarned()
  123. })
  124. })
  125. test('createPropsRestProxy', () => {
  126. const original = shallowReactive({
  127. foo: 1,
  128. bar: 2,
  129. baz: 3
  130. })
  131. const rest = createPropsRestProxy(original, ['foo', 'bar'])
  132. expect('foo' in rest).toBe(false)
  133. expect('bar' in rest).toBe(false)
  134. expect(rest.baz).toBe(3)
  135. expect(Object.keys(rest)).toEqual(['baz'])
  136. original.baz = 4
  137. expect(rest.baz).toBe(4)
  138. })
  139. describe('withAsyncContext', () => {
  140. // disable options API because applyOptions() also resets currentInstance
  141. // and we want to ensure the logic works even with Options API disabled.
  142. beforeEach(() => {
  143. __FEATURE_OPTIONS_API__ = false
  144. })
  145. afterEach(() => {
  146. __FEATURE_OPTIONS_API__ = true
  147. })
  148. test('basic', async () => {
  149. const spy = vi.fn()
  150. let beforeInstance: ComponentInternalInstance | null = null
  151. let afterInstance: ComponentInternalInstance | null = null
  152. let resolve: (msg: string) => void
  153. const Comp = defineComponent({
  154. async setup() {
  155. let __temp: any, __restore: any
  156. beforeInstance = getCurrentInstance()
  157. const msg =
  158. (([__temp, __restore] = withAsyncContext(
  159. () =>
  160. new Promise(r => {
  161. resolve = r
  162. })
  163. )),
  164. (__temp = await __temp),
  165. __restore(),
  166. __temp)
  167. // register the lifecycle after an await statement
  168. onMounted(spy)
  169. afterInstance = getCurrentInstance()
  170. return () => msg
  171. }
  172. })
  173. const root = nodeOps.createElement('div')
  174. render(
  175. h(() => h(Suspense, () => h(Comp))),
  176. root
  177. )
  178. expect(spy).not.toHaveBeenCalled()
  179. resolve!('hello')
  180. // wait a macro task tick for all micro ticks to resolve
  181. await new Promise(r => setTimeout(r))
  182. // mount hook should have been called
  183. expect(spy).toHaveBeenCalled()
  184. // should retain same instance before/after the await call
  185. expect(beforeInstance).toBe(afterInstance)
  186. expect(serializeInner(root)).toBe('hello')
  187. })
  188. test('error handling', async () => {
  189. const spy = vi.fn()
  190. let beforeInstance: ComponentInternalInstance | null = null
  191. let afterInstance: ComponentInternalInstance | null = null
  192. let reject: () => void
  193. const Comp = defineComponent({
  194. async setup() {
  195. let __temp: any, __restore: any
  196. beforeInstance = getCurrentInstance()
  197. try {
  198. ;[__temp, __restore] = withAsyncContext(
  199. () =>
  200. new Promise((_, rj) => {
  201. reject = rj
  202. })
  203. )
  204. __temp = await __temp
  205. __restore()
  206. } catch (e: any) {
  207. // ignore
  208. }
  209. // register the lifecycle after an await statement
  210. onMounted(spy)
  211. afterInstance = getCurrentInstance()
  212. return () => ''
  213. }
  214. })
  215. const root = nodeOps.createElement('div')
  216. render(
  217. h(() => h(Suspense, () => h(Comp))),
  218. root
  219. )
  220. expect(spy).not.toHaveBeenCalled()
  221. reject!()
  222. // wait a macro task tick for all micro ticks to resolve
  223. await new Promise(r => setTimeout(r))
  224. // mount hook should have been called
  225. expect(spy).toHaveBeenCalled()
  226. // should retain same instance before/after the await call
  227. expect(beforeInstance).toBe(afterInstance)
  228. })
  229. test('should not leak instance on multiple awaits', async () => {
  230. let resolve: (val?: any) => void
  231. let beforeInstance: ComponentInternalInstance | null = null
  232. let afterInstance: ComponentInternalInstance | null = null
  233. let inBandInstance: ComponentInternalInstance | null = null
  234. let outOfBandInstance: ComponentInternalInstance | null = null
  235. const ready = new Promise(r => {
  236. resolve = r
  237. })
  238. async function doAsyncWork() {
  239. // should still have instance
  240. inBandInstance = getCurrentInstance()
  241. await Promise.resolve()
  242. // should not leak instance
  243. outOfBandInstance = getCurrentInstance()
  244. }
  245. const Comp = defineComponent({
  246. async setup() {
  247. let __temp: any, __restore: any
  248. beforeInstance = getCurrentInstance()
  249. // first await
  250. ;[__temp, __restore] = withAsyncContext(() => Promise.resolve())
  251. __temp = await __temp
  252. __restore()
  253. // setup exit, instance set to null, then resumed
  254. ;[__temp, __restore] = withAsyncContext(() => doAsyncWork())
  255. __temp = await __temp
  256. __restore()
  257. afterInstance = getCurrentInstance()
  258. return () => {
  259. resolve()
  260. return ''
  261. }
  262. }
  263. })
  264. const root = nodeOps.createElement('div')
  265. render(
  266. h(() => h(Suspense, () => h(Comp))),
  267. root
  268. )
  269. await ready
  270. expect(inBandInstance).toBe(beforeInstance)
  271. expect(outOfBandInstance).toBeNull()
  272. expect(afterInstance).toBe(beforeInstance)
  273. expect(getCurrentInstance()).toBeNull()
  274. })
  275. test('should not leak on multiple awaits + error', async () => {
  276. let resolve: (val?: any) => void
  277. const ready = new Promise(r => {
  278. resolve = r
  279. })
  280. const Comp = defineComponent({
  281. async setup() {
  282. let __temp: any, __restore: any
  283. ;[__temp, __restore] = withAsyncContext(() => Promise.resolve())
  284. __temp = await __temp
  285. __restore()
  286. ;[__temp, __restore] = withAsyncContext(() => Promise.reject())
  287. __temp = await __temp
  288. __restore()
  289. },
  290. render() {}
  291. })
  292. const app = createApp(() => h(Suspense, () => h(Comp)))
  293. app.config.errorHandler = () => {
  294. resolve()
  295. return false
  296. }
  297. const root = nodeOps.createElement('div')
  298. app.mount(root)
  299. await ready
  300. expect(getCurrentInstance()).toBeNull()
  301. })
  302. // #4050
  303. test('race conditions', async () => {
  304. const uids = {
  305. one: { before: NaN, after: NaN },
  306. two: { before: NaN, after: NaN }
  307. }
  308. const Comp = defineComponent({
  309. props: ['name'],
  310. async setup(props: { name: 'one' | 'two' }) {
  311. let __temp: any, __restore: any
  312. uids[props.name].before = getCurrentInstance()!.uid
  313. ;[__temp, __restore] = withAsyncContext(() => Promise.resolve())
  314. __temp = await __temp
  315. __restore()
  316. uids[props.name].after = getCurrentInstance()!.uid
  317. return () => ''
  318. }
  319. })
  320. const app = createApp(() =>
  321. h(Suspense, () =>
  322. h('div', [h(Comp, { name: 'one' }), h(Comp, { name: 'two' })])
  323. )
  324. )
  325. const root = nodeOps.createElement('div')
  326. app.mount(root)
  327. await new Promise(r => setTimeout(r))
  328. expect(uids.one.before).not.toBe(uids.two.before)
  329. expect(uids.one.before).toBe(uids.one.after)
  330. expect(uids.two.before).toBe(uids.two.after)
  331. })
  332. test('should teardown in-scope effects', async () => {
  333. let resolve: (val?: any) => void
  334. const ready = new Promise(r => {
  335. resolve = r
  336. })
  337. let c: ComputedRef
  338. const Comp = defineComponent({
  339. async setup() {
  340. let __temp: any, __restore: any
  341. ;[__temp, __restore] = withAsyncContext(() => Promise.resolve())
  342. __temp = await __temp
  343. __restore()
  344. c = computed(() => {})
  345. // register the lifecycle after an await statement
  346. onMounted(resolve)
  347. return () => ''
  348. }
  349. })
  350. const app = createApp(() => h(Suspense, () => h(Comp)))
  351. const root = nodeOps.createElement('div')
  352. app.mount(root)
  353. await ready
  354. expect(c!.effect.active).toBe(true)
  355. app.unmount()
  356. expect(c!.effect.active).toBe(false)
  357. })
  358. })
  359. })