apiSetupHelpers.spec.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608
  1. import {
  2. type ComputedRefImpl,
  3. type ReactiveEffectRunner,
  4. effect,
  5. } from '@vue/reactivity'
  6. import {
  7. type ComponentInternalInstance,
  8. type SetupContext,
  9. Suspense,
  10. computed,
  11. createApp,
  12. defineComponent,
  13. getCurrentInstance,
  14. h,
  15. nodeOps,
  16. onMounted,
  17. render,
  18. serializeInner,
  19. shallowReactive,
  20. } from '@vue/runtime-test'
  21. import {
  22. createPropsRestProxy,
  23. defineEmits,
  24. defineExpose,
  25. defineProps,
  26. mergeDefaults,
  27. mergeModels,
  28. useAttrs,
  29. useSlots,
  30. withAsyncContext,
  31. withDefaults,
  32. } from '../src/apiSetupHelpers'
  33. describe('SFC <script setup> helpers', () => {
  34. test('should warn runtime usage', () => {
  35. defineProps()
  36. expect(`defineProps() is a compiler-hint`).toHaveBeenWarned()
  37. defineEmits()
  38. expect(`defineEmits() is a compiler-hint`).toHaveBeenWarned()
  39. defineExpose()
  40. expect(`defineExpose() is a compiler-hint`).toHaveBeenWarned()
  41. withDefaults({}, {})
  42. expect(`withDefaults() is a compiler-hint`).toHaveBeenWarned()
  43. })
  44. test('useSlots / useAttrs (no args)', () => {
  45. let slots: SetupContext['slots'] | undefined
  46. let attrs: SetupContext['attrs'] | undefined
  47. const Comp = {
  48. setup() {
  49. slots = useSlots()
  50. attrs = useAttrs()
  51. return () => {}
  52. },
  53. }
  54. const passedAttrs = { id: 'foo' }
  55. const passedSlots = {
  56. default: () => {},
  57. x: () => {},
  58. }
  59. render(h(Comp, passedAttrs, passedSlots), nodeOps.createElement('div'))
  60. expect(typeof slots!.default).toBe('function')
  61. expect(typeof slots!.x).toBe('function')
  62. expect(attrs).toMatchObject(passedAttrs)
  63. })
  64. test('useSlots / useAttrs (with args)', () => {
  65. let slots: SetupContext['slots'] | undefined
  66. let attrs: SetupContext['attrs'] | undefined
  67. let ctx: SetupContext | undefined
  68. const Comp = defineComponent({
  69. setup(_, _ctx) {
  70. slots = useSlots()
  71. attrs = useAttrs()
  72. ctx = _ctx
  73. return () => {}
  74. },
  75. })
  76. render(h(Comp), nodeOps.createElement('div'))
  77. expect(slots).toBe(ctx!.slots)
  78. expect(attrs).toBe(ctx!.attrs)
  79. })
  80. describe('mergeDefaults', () => {
  81. test('object syntax', () => {
  82. const merged = mergeDefaults(
  83. {
  84. foo: null,
  85. bar: { type: String, required: false },
  86. baz: String,
  87. },
  88. {
  89. foo: 1,
  90. bar: 'baz',
  91. baz: 'qux',
  92. },
  93. )
  94. expect(merged).toMatchObject({
  95. foo: { default: 1 },
  96. bar: { type: String, required: false, default: 'baz' },
  97. baz: { type: String, default: 'qux' },
  98. })
  99. })
  100. test('array syntax', () => {
  101. const merged = mergeDefaults(['foo', 'bar', 'baz'], {
  102. foo: 1,
  103. bar: 'baz',
  104. baz: 'qux',
  105. })
  106. expect(merged).toMatchObject({
  107. foo: { default: 1 },
  108. bar: { default: 'baz' },
  109. baz: { default: 'qux' },
  110. })
  111. })
  112. test('merging with skipFactory', () => {
  113. const fn = () => {}
  114. const merged = mergeDefaults(['foo', 'bar', 'baz'], {
  115. foo: fn,
  116. __skip_foo: true,
  117. })
  118. expect(merged).toMatchObject({
  119. foo: { default: fn, skipFactory: true },
  120. })
  121. })
  122. test('should warn missing', () => {
  123. mergeDefaults({}, { foo: 1 })
  124. expect(
  125. `props default key "foo" has no corresponding declaration`,
  126. ).toHaveBeenWarned()
  127. })
  128. })
  129. describe('mergeModels', () => {
  130. test('array syntax', () => {
  131. expect(mergeModels(['foo', 'bar'], ['baz'])).toMatchObject([
  132. 'foo',
  133. 'bar',
  134. 'baz',
  135. ])
  136. })
  137. test('object syntax', () => {
  138. expect(
  139. mergeModels({ foo: null, bar: { required: true } }, ['baz']),
  140. ).toMatchObject({
  141. foo: null,
  142. bar: { required: true },
  143. baz: {},
  144. })
  145. expect(
  146. mergeModels(['baz'], { foo: null, bar: { required: true } }),
  147. ).toMatchObject({
  148. foo: null,
  149. bar: { required: true },
  150. baz: {},
  151. })
  152. })
  153. test('overwrite', () => {
  154. expect(
  155. mergeModels(
  156. { foo: null, bar: { required: true } },
  157. { bar: {}, baz: {} },
  158. ),
  159. ).toMatchObject({
  160. foo: null,
  161. bar: {},
  162. baz: {},
  163. })
  164. })
  165. })
  166. test('createPropsRestProxy', () => {
  167. const original = shallowReactive({
  168. foo: 1,
  169. bar: 2,
  170. baz: 3,
  171. })
  172. const rest = createPropsRestProxy(original, ['foo', 'bar'])
  173. expect('foo' in rest).toBe(false)
  174. expect('bar' in rest).toBe(false)
  175. expect(rest.baz).toBe(3)
  176. expect(Object.keys(rest)).toEqual(['baz'])
  177. original.baz = 4
  178. expect(rest.baz).toBe(4)
  179. })
  180. describe('withAsyncContext', () => {
  181. // disable options API because applyOptions() also resets currentInstance
  182. // and we want to ensure the logic works even with Options API disabled.
  183. beforeEach(() => {
  184. __FEATURE_OPTIONS_API__ = false
  185. })
  186. afterEach(() => {
  187. __FEATURE_OPTIONS_API__ = true
  188. })
  189. test('basic', async () => {
  190. const spy = vi.fn()
  191. let beforeInstance: ComponentInternalInstance | null = null
  192. let afterInstance: ComponentInternalInstance | null = null
  193. let resolve: (msg: string) => void
  194. const Comp = defineComponent({
  195. async setup() {
  196. let __temp: any, __restore: any
  197. beforeInstance = getCurrentInstance()
  198. const msg =
  199. (([__temp, __restore] = withAsyncContext(
  200. () =>
  201. new Promise(r => {
  202. resolve = r
  203. }),
  204. )),
  205. (__temp = await __temp),
  206. __restore(),
  207. __temp)
  208. // register the lifecycle after an await statement
  209. onMounted(spy)
  210. afterInstance = getCurrentInstance()
  211. return () => msg
  212. },
  213. })
  214. const root = nodeOps.createElement('div')
  215. render(
  216. h(() => h(Suspense, () => h(Comp))),
  217. root,
  218. )
  219. expect(spy).not.toHaveBeenCalled()
  220. resolve!('hello')
  221. // wait a macro task tick for all micro ticks to resolve
  222. await new Promise(r => setTimeout(r))
  223. // mount hook should have been called
  224. expect(spy).toHaveBeenCalled()
  225. // should retain same instance before/after the await call
  226. expect(beforeInstance).toBe(afterInstance)
  227. expect(serializeInner(root)).toBe('hello')
  228. })
  229. test('should not leak instance to user microtasks after restore', async () => {
  230. let leakedToUserMicrotask = false
  231. const Comp = defineComponent({
  232. async setup() {
  233. let __temp: any, __restore: any
  234. ;[__temp, __restore] = withAsyncContext(() => Promise.resolve())
  235. __temp = await __temp
  236. __restore()
  237. Promise.resolve().then(() => {
  238. leakedToUserMicrotask = getCurrentInstance() !== null
  239. })
  240. return () => ''
  241. },
  242. })
  243. const root = nodeOps.createElement('div')
  244. render(
  245. h(() => h(Suspense, () => h(Comp))),
  246. root,
  247. )
  248. await new Promise(r => setTimeout(r))
  249. expect(leakedToUserMicrotask).toBe(false)
  250. })
  251. test('should not leak sibling instance in concurrent restores', async () => {
  252. let resolveOne: () => void
  253. let resolveTwo: () => void
  254. let done!: () => void
  255. let pending = 2
  256. const ready = new Promise<void>(r => {
  257. done = r
  258. })
  259. const seenUid: Record<'one' | 'two', number | null> = {
  260. one: null,
  261. two: null,
  262. }
  263. const makeComp = (name: 'one' | 'two', wait: Promise<void>) =>
  264. defineComponent({
  265. async setup() {
  266. let __temp: any, __restore: any
  267. ;[__temp, __restore] = withAsyncContext(() => wait)
  268. __temp = await __temp
  269. __restore()
  270. Promise.resolve().then(() => {
  271. seenUid[name] = getCurrentInstance()?.uid ?? null
  272. if (--pending === 0) done()
  273. })
  274. return () => ''
  275. },
  276. })
  277. const oneReady = new Promise<void>(r => {
  278. resolveOne = r
  279. })
  280. const twoReady = new Promise<void>(r => {
  281. resolveTwo = r
  282. })
  283. const CompOne = makeComp('one', oneReady)
  284. const CompTwo = makeComp('two', twoReady)
  285. const root = nodeOps.createElement('div')
  286. render(
  287. h(() => h(Suspense, () => h('div', [h(CompOne), h(CompTwo)]))),
  288. root,
  289. )
  290. resolveOne!()
  291. resolveTwo!()
  292. await ready
  293. expect(seenUid.one).toBeNull()
  294. expect(seenUid.two).toBeNull()
  295. })
  296. test('should not leak currentInstance to sibling slot render', async () => {
  297. let done!: () => void
  298. const ready = new Promise<void>(r => {
  299. done = r
  300. })
  301. let innerUid: number | null = null
  302. let innerRenderUid: number | null = null
  303. const Inner = defineComponent({
  304. setup(_, { slots }) {
  305. innerUid = getCurrentInstance()!.uid
  306. return () => {
  307. innerRenderUid = getCurrentInstance()!.uid
  308. done()
  309. return h('div', slots.default?.())
  310. }
  311. },
  312. })
  313. const Outer = defineComponent({
  314. setup(_, { slots }) {
  315. return () => h(Inner, null, () => [slots.default?.()])
  316. },
  317. })
  318. const AsyncA = defineComponent({
  319. async setup() {
  320. let __temp: any, __restore: any
  321. ;[__temp, __restore] = withAsyncContext(() =>
  322. Promise.resolve()
  323. .then(() => {})
  324. .then(() => {}),
  325. )
  326. __temp = await __temp
  327. __restore()
  328. return () => h('div', 'A')
  329. },
  330. })
  331. const AsyncB = defineComponent({
  332. async setup() {
  333. let __temp: any, __restore: any
  334. ;[__temp, __restore] = withAsyncContext(() => Promise.resolve())
  335. __temp = await __temp
  336. __restore()
  337. return () => h(Outer, null, () => 'B')
  338. },
  339. })
  340. const root = nodeOps.createElement('div')
  341. render(
  342. h(() => h(Suspense, () => h('div', [h(AsyncA), h(AsyncB)]))),
  343. root,
  344. )
  345. await ready
  346. expect(
  347. 'Slot "default" invoked outside of the render function',
  348. ).not.toHaveBeenWarned()
  349. expect(innerRenderUid).toBe(innerUid)
  350. await Promise.resolve()
  351. expect(serializeInner(root)).toBe(`<div><div>A</div><div>B</div></div>`)
  352. })
  353. test('error handling', async () => {
  354. const spy = vi.fn()
  355. let beforeInstance: ComponentInternalInstance | null = null
  356. let afterInstance: ComponentInternalInstance | null = null
  357. let reject: () => void
  358. const Comp = defineComponent({
  359. async setup() {
  360. let __temp: any, __restore: any
  361. beforeInstance = getCurrentInstance()
  362. try {
  363. ;[__temp, __restore] = withAsyncContext(
  364. () =>
  365. new Promise((_, rj) => {
  366. reject = rj
  367. }),
  368. )
  369. __temp = await __temp
  370. __restore()
  371. } catch (e: any) {
  372. // ignore
  373. }
  374. // register the lifecycle after an await statement
  375. onMounted(spy)
  376. afterInstance = getCurrentInstance()
  377. return () => ''
  378. },
  379. })
  380. const root = nodeOps.createElement('div')
  381. render(
  382. h(() => h(Suspense, () => h(Comp))),
  383. root,
  384. )
  385. expect(spy).not.toHaveBeenCalled()
  386. reject!()
  387. // wait a macro task tick for all micro ticks to resolve
  388. await new Promise(r => setTimeout(r))
  389. // mount hook should have been called
  390. expect(spy).toHaveBeenCalled()
  391. // should retain same instance before/after the await call
  392. expect(beforeInstance).toBe(afterInstance)
  393. })
  394. test('should not leak instance on multiple awaits', async () => {
  395. let resolve: (val?: any) => void
  396. let beforeInstance: ComponentInternalInstance | null = null
  397. let afterInstance: ComponentInternalInstance | null = null
  398. let inBandInstance: ComponentInternalInstance | null = null
  399. let outOfBandInstance: ComponentInternalInstance | null = null
  400. const ready = new Promise(r => {
  401. resolve = r
  402. })
  403. async function doAsyncWork() {
  404. // should still have instance
  405. inBandInstance = getCurrentInstance()
  406. await Promise.resolve()
  407. // should not leak instance
  408. outOfBandInstance = getCurrentInstance()
  409. }
  410. const Comp = defineComponent({
  411. async setup() {
  412. let __temp: any, __restore: any
  413. beforeInstance = getCurrentInstance()
  414. // first await
  415. ;[__temp, __restore] = withAsyncContext(() => Promise.resolve())
  416. __temp = await __temp
  417. __restore()
  418. // setup exit, instance set to null, then resumed
  419. ;[__temp, __restore] = withAsyncContext(() => doAsyncWork())
  420. __temp = await __temp
  421. __restore()
  422. afterInstance = getCurrentInstance()
  423. return () => {
  424. resolve()
  425. return ''
  426. }
  427. },
  428. })
  429. const root = nodeOps.createElement('div')
  430. render(
  431. h(() => h(Suspense, () => h(Comp))),
  432. root,
  433. )
  434. await ready
  435. expect(inBandInstance).toBe(beforeInstance)
  436. expect(outOfBandInstance).toBeNull()
  437. expect(afterInstance).toBe(beforeInstance)
  438. expect(getCurrentInstance()).toBeNull()
  439. })
  440. test('should not leak on multiple awaits + error', async () => {
  441. let resolve: (val?: any) => void
  442. const ready = new Promise(r => {
  443. resolve = r
  444. })
  445. const Comp = defineComponent({
  446. async setup() {
  447. let __temp: any, __restore: any
  448. ;[__temp, __restore] = withAsyncContext(() => Promise.resolve())
  449. __temp = await __temp
  450. __restore()
  451. ;[__temp, __restore] = withAsyncContext(() => Promise.reject())
  452. __temp = await __temp
  453. __restore()
  454. },
  455. render() {},
  456. })
  457. const app = createApp(() => h(Suspense, () => h(Comp)))
  458. app.config.errorHandler = () => {
  459. resolve()
  460. return false
  461. }
  462. const root = nodeOps.createElement('div')
  463. app.mount(root)
  464. await ready
  465. expect(getCurrentInstance()).toBeNull()
  466. })
  467. // #4050
  468. test('race conditions', async () => {
  469. const uids = {
  470. one: { before: NaN, after: NaN },
  471. two: { before: NaN, after: NaN },
  472. }
  473. const Comp = defineComponent({
  474. props: ['name'],
  475. async setup(props: { name: 'one' | 'two' }) {
  476. let __temp: any, __restore: any
  477. uids[props.name].before = getCurrentInstance()!.uid
  478. ;[__temp, __restore] = withAsyncContext(() => Promise.resolve())
  479. __temp = await __temp
  480. __restore()
  481. uids[props.name].after = getCurrentInstance()!.uid
  482. return () => ''
  483. },
  484. })
  485. const app = createApp(() =>
  486. h(Suspense, () =>
  487. h('div', [h(Comp, { name: 'one' }), h(Comp, { name: 'two' })]),
  488. ),
  489. )
  490. const root = nodeOps.createElement('div')
  491. app.mount(root)
  492. await new Promise(r => setTimeout(r))
  493. expect(uids.one.before).not.toBe(uids.two.before)
  494. expect(uids.one.before).toBe(uids.one.after)
  495. expect(uids.two.before).toBe(uids.two.after)
  496. })
  497. test('should teardown in-scope effects', async () => {
  498. let resolve: (val?: any) => void
  499. const ready = new Promise(r => {
  500. resolve = r
  501. })
  502. let c: ComputedRefImpl
  503. let e: ReactiveEffectRunner
  504. const Comp = defineComponent({
  505. async setup() {
  506. let __temp: any, __restore: any
  507. ;[__temp, __restore] = withAsyncContext(() => Promise.resolve())
  508. __temp = await __temp
  509. __restore()
  510. c = computed(() => {}) as unknown as ComputedRefImpl
  511. e = effect(() => c.value)
  512. // register the lifecycle after an await statement
  513. onMounted(resolve)
  514. return () => c.value
  515. },
  516. })
  517. const app = createApp(() => h(Suspense, () => h(Comp)))
  518. const root = nodeOps.createElement('div')
  519. app.mount(root)
  520. await ready
  521. expect(e!.effect.active).toBeTruthy()
  522. expect(c!.flags & 2 /* SubscriberFlags.Tracking */).toBe(0)
  523. app.unmount()
  524. expect(e!.effect.active).toBeFalsy()
  525. expect(c!.flags & 2 /* SubscriberFlags.Tracking */).toBe(0)
  526. })
  527. })
  528. })