definePropsDestructure.spec.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  1. import { BindingTypes } from '@vue/compiler-core'
  2. import type { SFCScriptCompileOptions } from '../../src'
  3. import { assertCode, compileSFCScript } from '../utils'
  4. describe('sfc reactive props destructure', () => {
  5. function compile(src: string, options?: Partial<SFCScriptCompileOptions>) {
  6. return compileSFCScript(src, {
  7. inlineTemplate: true,
  8. ...options,
  9. })
  10. }
  11. test('basic usage', () => {
  12. const { content, bindings } = compile(`
  13. <script setup>
  14. const { foo } = defineProps(['foo'])
  15. console.log(foo)
  16. </script>
  17. <template>{{ foo }}</template>
  18. `)
  19. expect(content).not.toMatch(`const { foo } =`)
  20. expect(content).toMatch(`console.log(__props.foo)`)
  21. expect(content).toMatch(`_toDisplayString(__props.foo)`)
  22. assertCode(content)
  23. expect(bindings).toStrictEqual({
  24. foo: BindingTypes.PROPS,
  25. })
  26. })
  27. test('multiple variable declarations', () => {
  28. const { content, bindings } = compile(`
  29. <script setup>
  30. const bar = 'fish', { foo } = defineProps(['foo']), hello = 'world'
  31. </script>
  32. <template><div>{{ foo }} {{ hello }} {{ bar }}</div></template>
  33. `)
  34. expect(content).not.toMatch(`const { foo } =`)
  35. expect(content).toMatch(`const bar = 'fish', hello = 'world'`)
  36. expect(content).toMatch(`_toDisplayString(hello)`)
  37. expect(content).toMatch(`_toDisplayString(bar)`)
  38. expect(content).toMatch(`_toDisplayString(__props.foo)`)
  39. assertCode(content)
  40. expect(bindings).toStrictEqual({
  41. foo: BindingTypes.PROPS,
  42. bar: BindingTypes.LITERAL_CONST,
  43. hello: BindingTypes.LITERAL_CONST,
  44. })
  45. })
  46. test('nested scope', () => {
  47. const { content, bindings } = compile(`
  48. <script setup>
  49. const { foo, bar } = defineProps(['foo', 'bar'])
  50. function test(foo) {
  51. console.log(foo)
  52. console.log(bar)
  53. }
  54. </script>
  55. `)
  56. expect(content).not.toMatch(`const { foo, bar } =`)
  57. expect(content).toMatch(`console.log(foo)`)
  58. expect(content).toMatch(`console.log(__props.bar)`)
  59. assertCode(content)
  60. expect(bindings).toStrictEqual({
  61. foo: BindingTypes.PROPS,
  62. bar: BindingTypes.PROPS,
  63. test: BindingTypes.SETUP_CONST,
  64. })
  65. })
  66. test('default values w/ array runtime declaration', () => {
  67. const { content } = compile(`
  68. <script setup>
  69. const { foo = 1, bar = {}, func = () => {} } = defineProps(['foo', 'bar', 'baz'])
  70. </script>
  71. `)
  72. // literals can be used as-is, non-literals are always returned from a
  73. // function
  74. // functions need to be marked with a skip marker
  75. expect(content)
  76. .toMatch(`props: /*#__PURE__*/_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: /*#__PURE__*/_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: /*#__PURE__*/_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. test('multi-variable declaration', () => {
  271. const { content } = compile(`
  272. <script setup>
  273. const { item } = defineProps(['item']),
  274. a = 1;
  275. </script>
  276. `)
  277. assertCode(content)
  278. expect(content).toMatch(`const a = 1;`)
  279. expect(content).toMatch(`props: ['item'],`)
  280. })
  281. // #6757
  282. test('multi-variable declaration fix #6757 ', () => {
  283. const { content } = compile(`
  284. <script setup>
  285. const a = 1,
  286. { item } = defineProps(['item']);
  287. </script>
  288. `)
  289. assertCode(content)
  290. expect(content).toMatch(`const a = 1;`)
  291. expect(content).toMatch(`props: ['item'],`)
  292. })
  293. // #7422
  294. test('multi-variable declaration fix #7422', () => {
  295. const { content } = compile(`
  296. <script setup>
  297. const { item } = defineProps(['item']),
  298. a = 0,
  299. b = 0;
  300. </script>
  301. `)
  302. assertCode(content)
  303. expect(content).toMatch(`const a = 0,`)
  304. expect(content).toMatch(`b = 0;`)
  305. expect(content).toMatch(`props: ['item'],`)
  306. })
  307. test('defineProps/defineEmits in multi-variable declaration (full removal)', () => {
  308. const { content } = compile(`
  309. <script setup>
  310. const props = defineProps(['item']),
  311. emit = defineEmits(['a']);
  312. </script>
  313. `)
  314. assertCode(content)
  315. expect(content).toMatch(`props: ['item'],`)
  316. expect(content).toMatch(`emits: ['a'],`)
  317. })
  318. describe('errors', () => {
  319. test('should error on deep destructure', () => {
  320. expect(() =>
  321. compile(
  322. `<script setup>const { foo: [bar] } = defineProps(['foo'])</script>`,
  323. ),
  324. ).toThrow(`destructure does not support nested patterns`)
  325. expect(() =>
  326. compile(
  327. `<script setup>const { foo: { bar } } = defineProps(['foo'])</script>`,
  328. ),
  329. ).toThrow(`destructure does not support nested patterns`)
  330. })
  331. test('should error on computed key', () => {
  332. expect(() =>
  333. compile(
  334. `<script setup>const { [foo]: bar } = defineProps(['foo'])</script>`,
  335. ),
  336. ).toThrow(`destructure cannot use computed key`)
  337. })
  338. test('should error when used with withDefaults', () => {
  339. expect(() =>
  340. compile(
  341. `<script setup lang="ts">
  342. const { foo } = withDefaults(defineProps<{ foo: string }>(), { foo: 'foo' })
  343. </script>`,
  344. ),
  345. ).toThrow(`withDefaults() is unnecessary when using destructure`)
  346. })
  347. test('should error if destructure reference local vars', () => {
  348. expect(() =>
  349. compile(
  350. `<script setup>
  351. let x = 1
  352. const {
  353. foo = () => x
  354. } = defineProps(['foo'])
  355. </script>`,
  356. ),
  357. ).toThrow(`cannot reference locally declared variables`)
  358. })
  359. test('should error if assignment to destructured prop binding', () => {
  360. expect(() =>
  361. compile(
  362. `<script setup>
  363. const { foo } = defineProps(['foo'])
  364. foo = 'bar'
  365. </script>`,
  366. ),
  367. ).toThrow(`Cannot assign to destructured props`)
  368. expect(() =>
  369. compile(
  370. `<script setup>
  371. let { foo } = defineProps(['foo'])
  372. foo = 'bar'
  373. </script>`,
  374. ),
  375. ).toThrow(`Cannot assign to destructured props`)
  376. })
  377. test('should error when passing destructured prop into certain methods', () => {
  378. expect(() =>
  379. compile(
  380. `<script setup>
  381. import { watch } from 'vue'
  382. const { foo } = defineProps(['foo'])
  383. watch(foo, () => {})
  384. </script>`,
  385. ),
  386. ).toThrow(
  387. `"foo" is a destructured prop and should not be passed directly to watch().`,
  388. )
  389. expect(() =>
  390. compile(
  391. `<script setup>
  392. import { watch as w } from 'vue'
  393. const { foo } = defineProps(['foo'])
  394. w(foo, () => {})
  395. </script>`,
  396. ),
  397. ).toThrow(
  398. `"foo" is a destructured prop and should not be passed directly to watch().`,
  399. )
  400. expect(() =>
  401. compile(
  402. `<script setup>
  403. import { toRef } from 'vue'
  404. const { foo } = defineProps(['foo'])
  405. toRef(foo)
  406. </script>`,
  407. ),
  408. ).toThrow(
  409. `"foo" is a destructured prop and should not be passed directly to toRef().`,
  410. )
  411. expect(() =>
  412. compile(
  413. `<script setup>
  414. import { toRef as r } from 'vue'
  415. const { foo } = defineProps(['foo'])
  416. r(foo)
  417. </script>`,
  418. ),
  419. ).toThrow(
  420. `"foo" is a destructured prop and should not be passed directly to toRef().`,
  421. )
  422. })
  423. // not comprehensive, but should help for most common cases
  424. test('should error if default value type does not match declared type', () => {
  425. expect(() =>
  426. compile(
  427. `<script setup lang="ts">
  428. const { foo = 'hello' } = defineProps<{ foo?: number }>()
  429. </script>`,
  430. ),
  431. ).toThrow(`Default value of prop "foo" does not match declared type.`)
  432. })
  433. // #8017
  434. test('should not throw an error if the variable is not a props', () => {
  435. expect(() =>
  436. compile(
  437. `<script setup lang='ts'>
  438. import { watch } from 'vue'
  439. const { userId } = defineProps({ userId: Number })
  440. const { error: e, info } = useRequest();
  441. watch(e, () => {});
  442. watch(info, () => {});
  443. </script>`,
  444. ),
  445. ).not.toThrowError()
  446. })
  447. })
  448. })