definePropsDestructure.spec.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  1. import { BindingTypes } from '@vue/compiler-core'
  2. import { SFCScriptCompileOptions } from '../../src'
  3. import { compileSFCScript, assertCode } from '../utils'
  4. describe('sfc reactive props destructure', () => {
  5. function compile(src: string, options?: Partial<SFCScriptCompileOptions>) {
  6. return compileSFCScript(src, {
  7. inlineTemplate: true,
  8. propsDestructure: true,
  9. ...options
  10. })
  11. }
  12. test('basic usage', () => {
  13. const { content, bindings } = compile(`
  14. <script setup>
  15. const { foo } = defineProps(['foo'])
  16. console.log(foo)
  17. </script>
  18. <template>{{ foo }}</template>
  19. `)
  20. expect(content).not.toMatch(`const { foo } =`)
  21. expect(content).toMatch(`console.log(__props.foo)`)
  22. expect(content).toMatch(`_toDisplayString(__props.foo)`)
  23. assertCode(content)
  24. expect(bindings).toStrictEqual({
  25. foo: BindingTypes.PROPS
  26. })
  27. })
  28. test('multiple variable declarations', () => {
  29. const { content, bindings } = compile(`
  30. <script setup>
  31. const bar = 'fish', { foo } = defineProps(['foo']), hello = 'world'
  32. </script>
  33. <template><div>{{ foo }} {{ hello }} {{ bar }}</div></template>
  34. `)
  35. expect(content).not.toMatch(`const { foo } =`)
  36. expect(content).toMatch(`const bar = 'fish', hello = 'world'`)
  37. expect(content).toMatch(`_toDisplayString(hello)`)
  38. expect(content).toMatch(`_toDisplayString(bar)`)
  39. expect(content).toMatch(`_toDisplayString(__props.foo)`)
  40. assertCode(content)
  41. expect(bindings).toStrictEqual({
  42. foo: BindingTypes.PROPS,
  43. bar: BindingTypes.LITERAL_CONST,
  44. hello: BindingTypes.LITERAL_CONST
  45. })
  46. })
  47. test('nested scope', () => {
  48. const { content, bindings } = compile(`
  49. <script setup>
  50. const { foo, bar } = defineProps(['foo', 'bar'])
  51. function test(foo) {
  52. console.log(foo)
  53. console.log(bar)
  54. }
  55. </script>
  56. `)
  57. expect(content).not.toMatch(`const { foo, bar } =`)
  58. expect(content).toMatch(`console.log(foo)`)
  59. expect(content).toMatch(`console.log(__props.bar)`)
  60. assertCode(content)
  61. expect(bindings).toStrictEqual({
  62. foo: BindingTypes.PROPS,
  63. bar: BindingTypes.PROPS,
  64. test: BindingTypes.SETUP_CONST
  65. })
  66. })
  67. test('default values w/ array runtime declaration', () => {
  68. const { content } = compile(`
  69. <script setup>
  70. const { foo = 1, bar = {}, func = () => {} } = defineProps(['foo', 'bar', 'baz'])
  71. </script>
  72. `)
  73. // literals can be used as-is, non-literals are always returned from a
  74. // function
  75. // functions need to be marked with a skip marker
  76. expect(content).toMatch(`props: _mergeDefaults(['foo', 'bar', 'baz'], {
  77. foo: 1,
  78. bar: () => ({}),
  79. func: () => {}, __skip_func: true
  80. })`)
  81. assertCode(content)
  82. })
  83. test('default values w/ object runtime declaration', () => {
  84. const { content } = compile(`
  85. <script setup>
  86. const { foo = 1, bar = {}, func = () => {}, ext = x } = defineProps({ foo: Number, bar: Object, func: Function, ext: null })
  87. </script>
  88. `)
  89. // literals can be used as-is, non-literals are always returned from a
  90. // function
  91. // functions need to be marked with a skip marker since we cannot always
  92. // safely infer whether runtime type is Function (e.g. if the runtime decl
  93. // is imported, or spreads another object)
  94. expect(content)
  95. .toMatch(`props: _mergeDefaults({ foo: Number, bar: Object, func: Function, ext: null }, {
  96. foo: 1,
  97. bar: () => ({}),
  98. func: () => {}, __skip_func: true,
  99. ext: x, __skip_ext: true
  100. })`)
  101. assertCode(content)
  102. })
  103. test('default values w/ runtime declaration & key is string', () => {
  104. const { content, bindings } = compile(`
  105. <script setup>
  106. const { foo = 1, 'foo:bar': fooBar = 'foo-bar' } = defineProps(['foo', 'foo:bar'])
  107. </script>
  108. `)
  109. expect(bindings).toStrictEqual({
  110. __propsAliases: {
  111. fooBar: 'foo:bar'
  112. },
  113. foo: BindingTypes.PROPS,
  114. 'foo:bar': BindingTypes.PROPS,
  115. fooBar: BindingTypes.PROPS_ALIASED
  116. })
  117. expect(content).toMatch(`
  118. props: _mergeDefaults(['foo', 'foo:bar'], {
  119. foo: 1,
  120. "foo:bar": 'foo-bar'
  121. }),`)
  122. assertCode(content)
  123. })
  124. test('default values w/ type declaration', () => {
  125. const { content } = compile(`
  126. <script setup lang="ts">
  127. const { foo = 1, bar = {}, func = () => {} } = defineProps<{ foo?: number, bar?: object, func?: () => any }>()
  128. </script>
  129. `)
  130. // literals can be used as-is, non-literals are always returned from a
  131. // function
  132. expect(content).toMatch(`props: {
  133. foo: { type: Number, required: false, default: 1 },
  134. bar: { type: Object, required: false, default: () => ({}) },
  135. func: { type: Function, required: false, default: () => {} }
  136. }`)
  137. assertCode(content)
  138. })
  139. test('default values w/ type declaration & key is string', () => {
  140. const { content, bindings } = compile(`
  141. <script setup lang="ts">
  142. const { foo = 1, bar = 2, 'foo:bar': fooBar = 'foo-bar' } = defineProps<{
  143. "foo": number // double-quoted string
  144. 'bar': number // single-quoted string
  145. 'foo:bar': string // single-quoted string containing symbols
  146. "onUpdate:modelValue": (val: number) => void // double-quoted string containing symbols
  147. }>()
  148. </script>
  149. `)
  150. expect(bindings).toStrictEqual({
  151. __propsAliases: {
  152. fooBar: 'foo:bar'
  153. },
  154. foo: BindingTypes.PROPS,
  155. bar: BindingTypes.PROPS,
  156. 'foo:bar': BindingTypes.PROPS,
  157. fooBar: BindingTypes.PROPS_ALIASED,
  158. 'onUpdate:modelValue': BindingTypes.PROPS
  159. })
  160. expect(content).toMatch(`
  161. props: {
  162. foo: { type: Number, required: true, default: 1 },
  163. bar: { type: Number, required: true, default: 2 },
  164. "foo:bar": { type: String, required: true, default: 'foo-bar' },
  165. "onUpdate:modelValue": { type: Function, required: true }
  166. },`)
  167. assertCode(content)
  168. })
  169. test('default values w/ type declaration, prod mode', () => {
  170. const { content } = compile(
  171. `
  172. <script setup lang="ts">
  173. const { foo = 1, bar = {}, func = () => {} } = defineProps<{ foo?: number, bar?: object, baz?: any, boola?: boolean, boolb?: boolean | number, func?: Function }>()
  174. </script>
  175. `,
  176. { isProd: true }
  177. )
  178. assertCode(content)
  179. // literals can be used as-is, non-literals are always returned from a
  180. // function
  181. expect(content).toMatch(`props: {
  182. foo: { default: 1 },
  183. bar: { default: () => ({}) },
  184. baz: {},
  185. boola: { type: Boolean },
  186. boolb: { type: [Boolean, Number] },
  187. func: { type: Function, default: () => {} }
  188. }`)
  189. })
  190. test('aliasing', () => {
  191. const { content, bindings } = compile(`
  192. <script setup>
  193. const { foo: bar } = defineProps(['foo'])
  194. let x = foo
  195. let y = bar
  196. </script>
  197. <template>{{ foo + bar }}</template>
  198. `)
  199. expect(content).not.toMatch(`const { foo: bar } =`)
  200. expect(content).toMatch(`let x = foo`) // should not process
  201. expect(content).toMatch(`let y = __props.foo`)
  202. // should convert bar to __props.foo in template expressions
  203. expect(content).toMatch(`_toDisplayString(__props.foo + __props.foo)`)
  204. assertCode(content)
  205. expect(bindings).toStrictEqual({
  206. x: BindingTypes.SETUP_LET,
  207. y: BindingTypes.SETUP_LET,
  208. foo: BindingTypes.PROPS,
  209. bar: BindingTypes.PROPS_ALIASED,
  210. __propsAliases: {
  211. bar: 'foo'
  212. }
  213. })
  214. })
  215. // #5425
  216. test('non-identifier prop names', () => {
  217. const { content, bindings } = compile(`
  218. <script setup>
  219. const { 'foo.bar': fooBar } = defineProps({ 'foo.bar': Function })
  220. let x = fooBar
  221. </script>
  222. <template>{{ fooBar }}</template>
  223. `)
  224. expect(content).toMatch(`x = __props["foo.bar"]`)
  225. expect(content).toMatch(`toDisplayString(__props["foo.bar"])`)
  226. assertCode(content)
  227. expect(bindings).toStrictEqual({
  228. x: BindingTypes.SETUP_LET,
  229. 'foo.bar': BindingTypes.PROPS,
  230. fooBar: BindingTypes.PROPS_ALIASED,
  231. __propsAliases: {
  232. fooBar: 'foo.bar'
  233. }
  234. })
  235. })
  236. test('rest spread', () => {
  237. const { content, bindings } = compile(`
  238. <script setup>
  239. const { foo, bar, ...rest } = defineProps(['foo', 'bar', 'baz'])
  240. </script>
  241. `)
  242. expect(content).toMatch(
  243. `const rest = _createPropsRestProxy(__props, ["foo","bar"])`
  244. )
  245. assertCode(content)
  246. expect(bindings).toStrictEqual({
  247. foo: BindingTypes.PROPS,
  248. bar: BindingTypes.PROPS,
  249. baz: BindingTypes.PROPS,
  250. rest: BindingTypes.SETUP_REACTIVE_CONST
  251. })
  252. })
  253. // #6960
  254. test('computed static key', () => {
  255. const { content, bindings } = compile(`
  256. <script setup>
  257. const { ['foo']: foo } = defineProps(['foo'])
  258. console.log(foo)
  259. </script>
  260. <template>{{ foo }}</template>
  261. `)
  262. expect(content).not.toMatch(`const { foo } =`)
  263. expect(content).toMatch(`console.log(__props.foo)`)
  264. expect(content).toMatch(`_toDisplayString(__props.foo)`)
  265. assertCode(content)
  266. expect(bindings).toStrictEqual({
  267. foo: BindingTypes.PROPS
  268. })
  269. })
  270. describe('errors', () => {
  271. test('should error on deep destructure', () => {
  272. expect(() =>
  273. compile(
  274. `<script setup>const { foo: [bar] } = defineProps(['foo'])</script>`
  275. )
  276. ).toThrow(`destructure does not support nested patterns`)
  277. expect(() =>
  278. compile(
  279. `<script setup>const { foo: { bar } } = defineProps(['foo'])</script>`
  280. )
  281. ).toThrow(`destructure does not support nested patterns`)
  282. })
  283. test('should error on computed key', () => {
  284. expect(() =>
  285. compile(
  286. `<script setup>const { [foo]: bar } = defineProps(['foo'])</script>`
  287. )
  288. ).toThrow(`destructure cannot use computed key`)
  289. })
  290. test('should error when used with withDefaults', () => {
  291. expect(() =>
  292. compile(
  293. `<script setup lang="ts">
  294. const { foo } = withDefaults(defineProps<{ foo: string }>(), { foo: 'foo' })
  295. </script>`
  296. )
  297. ).toThrow(`withDefaults() is unnecessary when using destructure`)
  298. })
  299. test('should error if destructure reference local vars', () => {
  300. expect(() =>
  301. compile(
  302. `<script setup>
  303. let x = 1
  304. const {
  305. foo = () => x
  306. } = defineProps(['foo'])
  307. </script>`
  308. )
  309. ).toThrow(`cannot reference locally declared variables`)
  310. })
  311. test('should error if assignment to destructured prop binding', () => {
  312. expect(() =>
  313. compile(
  314. `<script setup>
  315. const { foo } = defineProps(['foo'])
  316. foo = 'bar'
  317. </script>`
  318. )
  319. ).toThrow(`Cannot assign to destructured props`)
  320. expect(() =>
  321. compile(
  322. `<script setup>
  323. let { foo } = defineProps(['foo'])
  324. foo = 'bar'
  325. </script>`
  326. )
  327. ).toThrow(`Cannot assign to destructured props`)
  328. })
  329. test('should error when passing destructured prop into certain methods', () => {
  330. expect(() =>
  331. compile(
  332. `<script setup>
  333. import { watch } from 'vue'
  334. const { foo } = defineProps(['foo'])
  335. watch(foo, () => {})
  336. </script>`
  337. )
  338. ).toThrow(
  339. `"foo" is a destructured prop and should not be passed directly to watch().`
  340. )
  341. expect(() =>
  342. compile(
  343. `<script setup>
  344. import { watch as w } from 'vue'
  345. const { foo } = defineProps(['foo'])
  346. w(foo, () => {})
  347. </script>`
  348. )
  349. ).toThrow(
  350. `"foo" is a destructured prop and should not be passed directly to watch().`
  351. )
  352. expect(() =>
  353. compile(
  354. `<script setup>
  355. import { toRef } from 'vue'
  356. const { foo } = defineProps(['foo'])
  357. toRef(foo)
  358. </script>`
  359. )
  360. ).toThrow(
  361. `"foo" is a destructured prop and should not be passed directly to toRef().`
  362. )
  363. expect(() =>
  364. compile(
  365. `<script setup>
  366. import { toRef as r } from 'vue'
  367. const { foo } = defineProps(['foo'])
  368. r(foo)
  369. </script>`
  370. )
  371. ).toThrow(
  372. `"foo" is a destructured prop and should not be passed directly to toRef().`
  373. )
  374. })
  375. // not comprehensive, but should help for most common cases
  376. test('should error if default value type does not match declared type', () => {
  377. expect(() =>
  378. compile(
  379. `<script setup lang="ts">
  380. const { foo = 'hello' } = defineProps<{ foo?: number }>()
  381. </script>`
  382. )
  383. ).toThrow(`Default value of prop "foo" does not match declared type.`)
  384. })
  385. // #8017
  386. test('should not throw an error if the variable is not a props', () => {
  387. expect(() =>
  388. compile(
  389. `<script setup lang='ts'>
  390. import { watch } from 'vue'
  391. const { userId } = defineProps({ userId: Number })
  392. const { error: e, info } = useRequest();
  393. watch(e, () => {});
  394. watch(info, () => {});
  395. </script>`
  396. )
  397. ).not.toThrowError()
  398. })
  399. })
  400. })