apiSetupHelpers.spec.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  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('error handling', async () => {
  230. const spy = vi.fn()
  231. let beforeInstance: ComponentInternalInstance | null = null
  232. let afterInstance: ComponentInternalInstance | null = null
  233. let reject: () => void
  234. const Comp = defineComponent({
  235. async setup() {
  236. let __temp: any, __restore: any
  237. beforeInstance = getCurrentInstance()
  238. try {
  239. ;[__temp, __restore] = withAsyncContext(
  240. () =>
  241. new Promise((_, rj) => {
  242. reject = rj
  243. }),
  244. )
  245. __temp = await __temp
  246. __restore()
  247. } catch (e: any) {
  248. // ignore
  249. }
  250. // register the lifecycle after an await statement
  251. onMounted(spy)
  252. afterInstance = getCurrentInstance()
  253. return () => ''
  254. },
  255. })
  256. const root = nodeOps.createElement('div')
  257. render(
  258. h(() => h(Suspense, () => h(Comp))),
  259. root,
  260. )
  261. expect(spy).not.toHaveBeenCalled()
  262. reject!()
  263. // wait a macro task tick for all micro ticks to resolve
  264. await new Promise(r => setTimeout(r))
  265. // mount hook should have been called
  266. expect(spy).toHaveBeenCalled()
  267. // should retain same instance before/after the await call
  268. expect(beforeInstance).toBe(afterInstance)
  269. })
  270. test('should not leak instance on multiple awaits', async () => {
  271. let resolve: (val?: any) => void
  272. let beforeInstance: ComponentInternalInstance | null = null
  273. let afterInstance: ComponentInternalInstance | null = null
  274. let inBandInstance: ComponentInternalInstance | null = null
  275. let outOfBandInstance: ComponentInternalInstance | null = null
  276. const ready = new Promise(r => {
  277. resolve = r
  278. })
  279. async function doAsyncWork() {
  280. // should still have instance
  281. inBandInstance = getCurrentInstance()
  282. await Promise.resolve()
  283. // should not leak instance
  284. outOfBandInstance = getCurrentInstance()
  285. }
  286. const Comp = defineComponent({
  287. async setup() {
  288. let __temp: any, __restore: any
  289. beforeInstance = getCurrentInstance()
  290. // first await
  291. ;[__temp, __restore] = withAsyncContext(() => Promise.resolve())
  292. __temp = await __temp
  293. __restore()
  294. // setup exit, instance set to null, then resumed
  295. ;[__temp, __restore] = withAsyncContext(() => doAsyncWork())
  296. __temp = await __temp
  297. __restore()
  298. afterInstance = getCurrentInstance()
  299. return () => {
  300. resolve()
  301. return ''
  302. }
  303. },
  304. })
  305. const root = nodeOps.createElement('div')
  306. render(
  307. h(() => h(Suspense, () => h(Comp))),
  308. root,
  309. )
  310. await ready
  311. expect(inBandInstance).toBe(beforeInstance)
  312. expect(outOfBandInstance).toBeNull()
  313. expect(afterInstance).toBe(beforeInstance)
  314. expect(getCurrentInstance()).toBeNull()
  315. })
  316. test('should not leak on multiple awaits + error', async () => {
  317. let resolve: (val?: any) => void
  318. const ready = new Promise(r => {
  319. resolve = r
  320. })
  321. const Comp = defineComponent({
  322. async setup() {
  323. let __temp: any, __restore: any
  324. ;[__temp, __restore] = withAsyncContext(() => Promise.resolve())
  325. __temp = await __temp
  326. __restore()
  327. ;[__temp, __restore] = withAsyncContext(() => Promise.reject())
  328. __temp = await __temp
  329. __restore()
  330. },
  331. render() {},
  332. })
  333. const app = createApp(() => h(Suspense, () => h(Comp)))
  334. app.config.errorHandler = () => {
  335. resolve()
  336. return false
  337. }
  338. const root = nodeOps.createElement('div')
  339. app.mount(root)
  340. await ready
  341. expect(getCurrentInstance()).toBeNull()
  342. })
  343. // #4050
  344. test('race conditions', async () => {
  345. const uids = {
  346. one: { before: NaN, after: NaN },
  347. two: { before: NaN, after: NaN },
  348. }
  349. const Comp = defineComponent({
  350. props: ['name'],
  351. async setup(props: { name: 'one' | 'two' }) {
  352. let __temp: any, __restore: any
  353. uids[props.name].before = getCurrentInstance()!.uid
  354. ;[__temp, __restore] = withAsyncContext(() => Promise.resolve())
  355. __temp = await __temp
  356. __restore()
  357. uids[props.name].after = getCurrentInstance()!.uid
  358. return () => ''
  359. },
  360. })
  361. const app = createApp(() =>
  362. h(Suspense, () =>
  363. h('div', [h(Comp, { name: 'one' }), h(Comp, { name: 'two' })]),
  364. ),
  365. )
  366. const root = nodeOps.createElement('div')
  367. app.mount(root)
  368. await new Promise(r => setTimeout(r))
  369. expect(uids.one.before).not.toBe(uids.two.before)
  370. expect(uids.one.before).toBe(uids.one.after)
  371. expect(uids.two.before).toBe(uids.two.after)
  372. })
  373. test('should teardown in-scope effects', async () => {
  374. let resolve: (val?: any) => void
  375. const ready = new Promise(r => {
  376. resolve = r
  377. })
  378. let c: ComputedRefImpl
  379. let e: ReactiveEffectRunner
  380. const Comp = defineComponent({
  381. async setup() {
  382. let __temp: any, __restore: any
  383. ;[__temp, __restore] = withAsyncContext(() => Promise.resolve())
  384. __temp = await __temp
  385. __restore()
  386. c = computed(() => {}) as unknown as ComputedRefImpl
  387. e = effect(() => c.value)
  388. // register the lifecycle after an await statement
  389. onMounted(resolve)
  390. return () => c.value
  391. },
  392. })
  393. const app = createApp(() => h(Suspense, () => h(Comp)))
  394. const root = nodeOps.createElement('div')
  395. app.mount(root)
  396. await ready
  397. expect(e!.effect.active).toBeTruthy()
  398. expect(c!.flags & 2 /* SubscriberFlags.Tracking */).toBe(0)
  399. app.unmount()
  400. expect(e!.effect.active).toBeFalsy()
  401. expect(c!.flags & 2 /* SubscriberFlags.Tracking */).toBe(0)
  402. })
  403. })
  404. })