apiSetupHelpers.spec.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  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('error handling', async () => {
  297. const spy = vi.fn()
  298. let beforeInstance: ComponentInternalInstance | null = null
  299. let afterInstance: ComponentInternalInstance | null = null
  300. let reject: () => void
  301. const Comp = defineComponent({
  302. async setup() {
  303. let __temp: any, __restore: any
  304. beforeInstance = getCurrentInstance()
  305. try {
  306. ;[__temp, __restore] = withAsyncContext(
  307. () =>
  308. new Promise((_, rj) => {
  309. reject = rj
  310. }),
  311. )
  312. __temp = await __temp
  313. __restore()
  314. } catch (e: any) {
  315. // ignore
  316. }
  317. // register the lifecycle after an await statement
  318. onMounted(spy)
  319. afterInstance = getCurrentInstance()
  320. return () => ''
  321. },
  322. })
  323. const root = nodeOps.createElement('div')
  324. render(
  325. h(() => h(Suspense, () => h(Comp))),
  326. root,
  327. )
  328. expect(spy).not.toHaveBeenCalled()
  329. reject!()
  330. // wait a macro task tick for all micro ticks to resolve
  331. await new Promise(r => setTimeout(r))
  332. // mount hook should have been called
  333. expect(spy).toHaveBeenCalled()
  334. // should retain same instance before/after the await call
  335. expect(beforeInstance).toBe(afterInstance)
  336. })
  337. test('should not leak instance on multiple awaits', async () => {
  338. let resolve: (val?: any) => void
  339. let beforeInstance: ComponentInternalInstance | null = null
  340. let afterInstance: ComponentInternalInstance | null = null
  341. let inBandInstance: ComponentInternalInstance | null = null
  342. let outOfBandInstance: ComponentInternalInstance | null = null
  343. const ready = new Promise(r => {
  344. resolve = r
  345. })
  346. async function doAsyncWork() {
  347. // should still have instance
  348. inBandInstance = getCurrentInstance()
  349. await Promise.resolve()
  350. // should not leak instance
  351. outOfBandInstance = getCurrentInstance()
  352. }
  353. const Comp = defineComponent({
  354. async setup() {
  355. let __temp: any, __restore: any
  356. beforeInstance = getCurrentInstance()
  357. // first await
  358. ;[__temp, __restore] = withAsyncContext(() => Promise.resolve())
  359. __temp = await __temp
  360. __restore()
  361. // setup exit, instance set to null, then resumed
  362. ;[__temp, __restore] = withAsyncContext(() => doAsyncWork())
  363. __temp = await __temp
  364. __restore()
  365. afterInstance = getCurrentInstance()
  366. return () => {
  367. resolve()
  368. return ''
  369. }
  370. },
  371. })
  372. const root = nodeOps.createElement('div')
  373. render(
  374. h(() => h(Suspense, () => h(Comp))),
  375. root,
  376. )
  377. await ready
  378. expect(inBandInstance).toBe(beforeInstance)
  379. expect(outOfBandInstance).toBeNull()
  380. expect(afterInstance).toBe(beforeInstance)
  381. expect(getCurrentInstance()).toBeNull()
  382. })
  383. test('should not leak on multiple awaits + error', async () => {
  384. let resolve: (val?: any) => void
  385. const ready = new Promise(r => {
  386. resolve = r
  387. })
  388. const Comp = defineComponent({
  389. async setup() {
  390. let __temp: any, __restore: any
  391. ;[__temp, __restore] = withAsyncContext(() => Promise.resolve())
  392. __temp = await __temp
  393. __restore()
  394. ;[__temp, __restore] = withAsyncContext(() => Promise.reject())
  395. __temp = await __temp
  396. __restore()
  397. },
  398. render() {},
  399. })
  400. const app = createApp(() => h(Suspense, () => h(Comp)))
  401. app.config.errorHandler = () => {
  402. resolve()
  403. return false
  404. }
  405. const root = nodeOps.createElement('div')
  406. app.mount(root)
  407. await ready
  408. expect(getCurrentInstance()).toBeNull()
  409. })
  410. // #4050
  411. test('race conditions', async () => {
  412. const uids = {
  413. one: { before: NaN, after: NaN },
  414. two: { before: NaN, after: NaN },
  415. }
  416. const Comp = defineComponent({
  417. props: ['name'],
  418. async setup(props: { name: 'one' | 'two' }) {
  419. let __temp: any, __restore: any
  420. uids[props.name].before = getCurrentInstance()!.uid
  421. ;[__temp, __restore] = withAsyncContext(() => Promise.resolve())
  422. __temp = await __temp
  423. __restore()
  424. uids[props.name].after = getCurrentInstance()!.uid
  425. return () => ''
  426. },
  427. })
  428. const app = createApp(() =>
  429. h(Suspense, () =>
  430. h('div', [h(Comp, { name: 'one' }), h(Comp, { name: 'two' })]),
  431. ),
  432. )
  433. const root = nodeOps.createElement('div')
  434. app.mount(root)
  435. await new Promise(r => setTimeout(r))
  436. expect(uids.one.before).not.toBe(uids.two.before)
  437. expect(uids.one.before).toBe(uids.one.after)
  438. expect(uids.two.before).toBe(uids.two.after)
  439. })
  440. test('should teardown in-scope effects', async () => {
  441. let resolve: (val?: any) => void
  442. const ready = new Promise(r => {
  443. resolve = r
  444. })
  445. let c: ComputedRefImpl
  446. let e: ReactiveEffectRunner
  447. const Comp = defineComponent({
  448. async setup() {
  449. let __temp: any, __restore: any
  450. ;[__temp, __restore] = withAsyncContext(() => Promise.resolve())
  451. __temp = await __temp
  452. __restore()
  453. c = computed(() => {}) as unknown as ComputedRefImpl
  454. e = effect(() => c.value)
  455. // register the lifecycle after an await statement
  456. onMounted(resolve)
  457. return () => c.value
  458. },
  459. })
  460. const app = createApp(() => h(Suspense, () => h(Comp)))
  461. const root = nodeOps.createElement('div')
  462. app.mount(root)
  463. await ready
  464. expect(e!.effect.active).toBeTruthy()
  465. expect(c!.flags & 2 /* SubscriberFlags.Tracking */).toBe(0)
  466. app.unmount()
  467. expect(e!.effect.active).toBeFalsy()
  468. expect(c!.flags & 2 /* SubscriberFlags.Tracking */).toBe(0)
  469. })
  470. })
  471. })