apiSetupHelpers.spec.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562
  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. nextTick,
  18. ref
  19. } from '@vue/runtime-test'
  20. import {
  21. defineEmits,
  22. defineProps,
  23. defineExpose,
  24. withDefaults,
  25. useAttrs,
  26. useSlots,
  27. mergeDefaults,
  28. withAsyncContext,
  29. createPropsRestProxy,
  30. mergeModels,
  31. useModel
  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. describe('useModel', () => {
  167. test('basic', async () => {
  168. let foo: any
  169. const update = () => {
  170. foo.value = 'bar'
  171. }
  172. const Comp = defineComponent({
  173. props: ['modelValue'],
  174. emits: ['update:modelValue'],
  175. setup(props) {
  176. foo = useModel(props, 'modelValue')
  177. },
  178. render() {}
  179. })
  180. const msg = ref('')
  181. const setValue = vi.fn(v => (msg.value = v))
  182. const root = nodeOps.createElement('div')
  183. createApp(() =>
  184. h(Comp, {
  185. modelValue: msg.value,
  186. 'onUpdate:modelValue': setValue
  187. })
  188. ).mount(root)
  189. expect(foo.value).toBe('')
  190. expect(msg.value).toBe('')
  191. expect(setValue).not.toBeCalled()
  192. // update from child
  193. update()
  194. await nextTick()
  195. expect(msg.value).toBe('bar')
  196. expect(foo.value).toBe('bar')
  197. expect(setValue).toBeCalledTimes(1)
  198. // update from parent
  199. msg.value = 'qux'
  200. await nextTick()
  201. expect(msg.value).toBe('qux')
  202. expect(foo.value).toBe('qux')
  203. expect(setValue).toBeCalledTimes(1)
  204. })
  205. test('local', async () => {
  206. let foo: any
  207. const update = () => {
  208. foo.value = 'bar'
  209. }
  210. const Comp = defineComponent({
  211. props: ['foo'],
  212. emits: ['update:foo'],
  213. setup(props) {
  214. foo = useModel(props, 'foo', { local: true })
  215. },
  216. render() {}
  217. })
  218. const root = nodeOps.createElement('div')
  219. const updateFoo = vi.fn()
  220. render(h(Comp, { 'onUpdate:foo': updateFoo }), root)
  221. expect(foo.value).toBeUndefined()
  222. update()
  223. expect(foo.value).toBe('bar')
  224. await nextTick()
  225. expect(updateFoo).toBeCalledTimes(1)
  226. })
  227. test('default value', async () => {
  228. let count: any
  229. const inc = () => {
  230. count.value++
  231. }
  232. const Comp = defineComponent({
  233. props: { count: { default: 0 } },
  234. emits: ['update:count'],
  235. setup(props) {
  236. count = useModel(props, 'count', { local: true })
  237. },
  238. render() {}
  239. })
  240. const root = nodeOps.createElement('div')
  241. const updateCount = vi.fn()
  242. render(h(Comp, { 'onUpdate:count': updateCount }), root)
  243. expect(count.value).toBe(0)
  244. inc()
  245. expect(count.value).toBe(1)
  246. await nextTick()
  247. expect(updateCount).toBeCalledTimes(1)
  248. })
  249. })
  250. test('createPropsRestProxy', () => {
  251. const original = shallowReactive({
  252. foo: 1,
  253. bar: 2,
  254. baz: 3
  255. })
  256. const rest = createPropsRestProxy(original, ['foo', 'bar'])
  257. expect('foo' in rest).toBe(false)
  258. expect('bar' in rest).toBe(false)
  259. expect(rest.baz).toBe(3)
  260. expect(Object.keys(rest)).toEqual(['baz'])
  261. original.baz = 4
  262. expect(rest.baz).toBe(4)
  263. })
  264. describe('withAsyncContext', () => {
  265. // disable options API because applyOptions() also resets currentInstance
  266. // and we want to ensure the logic works even with Options API disabled.
  267. beforeEach(() => {
  268. __FEATURE_OPTIONS_API__ = false
  269. })
  270. afterEach(() => {
  271. __FEATURE_OPTIONS_API__ = true
  272. })
  273. test('basic', async () => {
  274. const spy = vi.fn()
  275. let beforeInstance: ComponentInternalInstance | null = null
  276. let afterInstance: ComponentInternalInstance | null = null
  277. let resolve: (msg: string) => void
  278. const Comp = defineComponent({
  279. async setup() {
  280. let __temp: any, __restore: any
  281. beforeInstance = getCurrentInstance()
  282. const msg =
  283. (([__temp, __restore] = withAsyncContext(
  284. () =>
  285. new Promise(r => {
  286. resolve = r
  287. })
  288. )),
  289. (__temp = await __temp),
  290. __restore(),
  291. __temp)
  292. // register the lifecycle after an await statement
  293. onMounted(spy)
  294. afterInstance = getCurrentInstance()
  295. return () => msg
  296. }
  297. })
  298. const root = nodeOps.createElement('div')
  299. render(
  300. h(() => h(Suspense, () => h(Comp))),
  301. root
  302. )
  303. expect(spy).not.toHaveBeenCalled()
  304. resolve!('hello')
  305. // wait a macro task tick for all micro ticks to resolve
  306. await new Promise(r => setTimeout(r))
  307. // mount hook should have been called
  308. expect(spy).toHaveBeenCalled()
  309. // should retain same instance before/after the await call
  310. expect(beforeInstance).toBe(afterInstance)
  311. expect(serializeInner(root)).toBe('hello')
  312. })
  313. test('error handling', async () => {
  314. const spy = vi.fn()
  315. let beforeInstance: ComponentInternalInstance | null = null
  316. let afterInstance: ComponentInternalInstance | null = null
  317. let reject: () => void
  318. const Comp = defineComponent({
  319. async setup() {
  320. let __temp: any, __restore: any
  321. beforeInstance = getCurrentInstance()
  322. try {
  323. ;[__temp, __restore] = withAsyncContext(
  324. () =>
  325. new Promise((_, rj) => {
  326. reject = rj
  327. })
  328. )
  329. __temp = await __temp
  330. __restore()
  331. } catch (e: any) {
  332. // ignore
  333. }
  334. // register the lifecycle after an await statement
  335. onMounted(spy)
  336. afterInstance = getCurrentInstance()
  337. return () => ''
  338. }
  339. })
  340. const root = nodeOps.createElement('div')
  341. render(
  342. h(() => h(Suspense, () => h(Comp))),
  343. root
  344. )
  345. expect(spy).not.toHaveBeenCalled()
  346. reject!()
  347. // wait a macro task tick for all micro ticks to resolve
  348. await new Promise(r => setTimeout(r))
  349. // mount hook should have been called
  350. expect(spy).toHaveBeenCalled()
  351. // should retain same instance before/after the await call
  352. expect(beforeInstance).toBe(afterInstance)
  353. })
  354. test('should not leak instance on multiple awaits', async () => {
  355. let resolve: (val?: any) => void
  356. let beforeInstance: ComponentInternalInstance | null = null
  357. let afterInstance: ComponentInternalInstance | null = null
  358. let inBandInstance: ComponentInternalInstance | null = null
  359. let outOfBandInstance: ComponentInternalInstance | null = null
  360. const ready = new Promise(r => {
  361. resolve = r
  362. })
  363. async function doAsyncWork() {
  364. // should still have instance
  365. inBandInstance = getCurrentInstance()
  366. await Promise.resolve()
  367. // should not leak instance
  368. outOfBandInstance = getCurrentInstance()
  369. }
  370. const Comp = defineComponent({
  371. async setup() {
  372. let __temp: any, __restore: any
  373. beforeInstance = getCurrentInstance()
  374. // first await
  375. ;[__temp, __restore] = withAsyncContext(() => Promise.resolve())
  376. __temp = await __temp
  377. __restore()
  378. // setup exit, instance set to null, then resumed
  379. ;[__temp, __restore] = withAsyncContext(() => doAsyncWork())
  380. __temp = await __temp
  381. __restore()
  382. afterInstance = getCurrentInstance()
  383. return () => {
  384. resolve()
  385. return ''
  386. }
  387. }
  388. })
  389. const root = nodeOps.createElement('div')
  390. render(
  391. h(() => h(Suspense, () => h(Comp))),
  392. root
  393. )
  394. await ready
  395. expect(inBandInstance).toBe(beforeInstance)
  396. expect(outOfBandInstance).toBeNull()
  397. expect(afterInstance).toBe(beforeInstance)
  398. expect(getCurrentInstance()).toBeNull()
  399. })
  400. test('should not leak on multiple awaits + error', async () => {
  401. let resolve: (val?: any) => void
  402. const ready = new Promise(r => {
  403. resolve = r
  404. })
  405. const Comp = defineComponent({
  406. async setup() {
  407. let __temp: any, __restore: any
  408. ;[__temp, __restore] = withAsyncContext(() => Promise.resolve())
  409. __temp = await __temp
  410. __restore()
  411. ;[__temp, __restore] = withAsyncContext(() => Promise.reject())
  412. __temp = await __temp
  413. __restore()
  414. },
  415. render() {}
  416. })
  417. const app = createApp(() => h(Suspense, () => h(Comp)))
  418. app.config.errorHandler = () => {
  419. resolve()
  420. return false
  421. }
  422. const root = nodeOps.createElement('div')
  423. app.mount(root)
  424. await ready
  425. expect(getCurrentInstance()).toBeNull()
  426. })
  427. // #4050
  428. test('race conditions', async () => {
  429. const uids = {
  430. one: { before: NaN, after: NaN },
  431. two: { before: NaN, after: NaN }
  432. }
  433. const Comp = defineComponent({
  434. props: ['name'],
  435. async setup(props: { name: 'one' | 'two' }) {
  436. let __temp: any, __restore: any
  437. uids[props.name].before = getCurrentInstance()!.uid
  438. ;[__temp, __restore] = withAsyncContext(() => Promise.resolve())
  439. __temp = await __temp
  440. __restore()
  441. uids[props.name].after = getCurrentInstance()!.uid
  442. return () => ''
  443. }
  444. })
  445. const app = createApp(() =>
  446. h(Suspense, () =>
  447. h('div', [h(Comp, { name: 'one' }), h(Comp, { name: 'two' })])
  448. )
  449. )
  450. const root = nodeOps.createElement('div')
  451. app.mount(root)
  452. await new Promise(r => setTimeout(r))
  453. expect(uids.one.before).not.toBe(uids.two.before)
  454. expect(uids.one.before).toBe(uids.one.after)
  455. expect(uids.two.before).toBe(uids.two.after)
  456. })
  457. test('should teardown in-scope effects', async () => {
  458. let resolve: (val?: any) => void
  459. const ready = new Promise(r => {
  460. resolve = r
  461. })
  462. let c: ComputedRef
  463. const Comp = defineComponent({
  464. async setup() {
  465. let __temp: any, __restore: any
  466. ;[__temp, __restore] = withAsyncContext(() => Promise.resolve())
  467. __temp = await __temp
  468. __restore()
  469. c = computed(() => {})
  470. // register the lifecycle after an await statement
  471. onMounted(resolve)
  472. return () => ''
  473. }
  474. })
  475. const app = createApp(() => h(Suspense, () => h(Comp)))
  476. const root = nodeOps.createElement('div')
  477. app.mount(root)
  478. await ready
  479. expect(c!.effect.active).toBe(true)
  480. app.unmount()
  481. expect(c!.effect.active).toBe(false)
  482. })
  483. })
  484. })