componentProps.spec.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677
  1. /**
  2. * @vitest-environment jsdom
  3. */
  4. import { vi } from 'vitest'
  5. import {
  6. ComponentInternalInstance,
  7. getCurrentInstance,
  8. render,
  9. h,
  10. nodeOps,
  11. FunctionalComponent,
  12. defineComponent,
  13. ref,
  14. serializeInner,
  15. createApp,
  16. provide,
  17. inject,
  18. watch,
  19. toRefs,
  20. SetupContext
  21. } from '@vue/runtime-test'
  22. import { render as domRender, nextTick } from 'vue'
  23. describe('component props', () => {
  24. test('stateful', () => {
  25. let props: any
  26. let attrs: any
  27. let proxy: any
  28. const Comp = defineComponent({
  29. props: ['fooBar', 'barBaz'],
  30. render() {
  31. props = this.$props
  32. attrs = this.$attrs
  33. proxy = this
  34. }
  35. })
  36. const root = nodeOps.createElement('div')
  37. render(h(Comp, { fooBar: 1, bar: 2 }), root)
  38. expect(proxy.fooBar).toBe(1)
  39. expect(props).toEqual({ fooBar: 1 })
  40. expect(attrs).toEqual({ bar: 2 })
  41. // test passing kebab-case and resolving to camelCase
  42. render(h(Comp, { 'foo-bar': 2, bar: 3, baz: 4 }), root)
  43. expect(proxy.fooBar).toBe(2)
  44. expect(props).toEqual({ fooBar: 2 })
  45. expect(attrs).toEqual({ bar: 3, baz: 4 })
  46. // test updating kebab-case should not delete it (#955)
  47. render(h(Comp, { 'foo-bar': 3, bar: 3, baz: 4, barBaz: 5 }), root)
  48. expect(proxy.fooBar).toBe(3)
  49. expect(proxy.barBaz).toBe(5)
  50. expect(props).toEqual({ fooBar: 3, barBaz: 5 })
  51. expect(attrs).toEqual({ bar: 3, baz: 4 })
  52. render(h(Comp, { qux: 5 }), root)
  53. expect(proxy.fooBar).toBeUndefined()
  54. // remove the props with camelCase key (#1412)
  55. expect(proxy.barBaz).toBeUndefined()
  56. expect(props).toEqual({})
  57. expect(attrs).toEqual({ qux: 5 })
  58. })
  59. test('stateful with setup', () => {
  60. let props: any
  61. let attrs: any
  62. const Comp = defineComponent({
  63. props: ['foo'],
  64. setup(_props, { attrs: _attrs }) {
  65. return () => {
  66. props = _props
  67. attrs = _attrs
  68. }
  69. }
  70. })
  71. const root = nodeOps.createElement('div')
  72. render(h(Comp, { foo: 1, bar: 2 }), root)
  73. expect(props).toEqual({ foo: 1 })
  74. expect(attrs).toEqual({ bar: 2 })
  75. render(h(Comp, { foo: 2, bar: 3, baz: 4 }), root)
  76. expect(props).toEqual({ foo: 2 })
  77. expect(attrs).toEqual({ bar: 3, baz: 4 })
  78. render(h(Comp, { qux: 5 }), root)
  79. expect(props).toEqual({})
  80. expect(attrs).toEqual({ qux: 5 })
  81. })
  82. test('functional with declaration', () => {
  83. let props: any
  84. let attrs: any
  85. const Comp: FunctionalComponent = (_props, { attrs: _attrs }) => {
  86. props = _props
  87. attrs = _attrs
  88. }
  89. Comp.props = ['foo']
  90. const root = nodeOps.createElement('div')
  91. render(h(Comp, { foo: 1, bar: 2 }), root)
  92. expect(props).toEqual({ foo: 1 })
  93. expect(attrs).toEqual({ bar: 2 })
  94. render(h(Comp, { foo: 2, bar: 3, baz: 4 }), root)
  95. expect(props).toEqual({ foo: 2 })
  96. expect(attrs).toEqual({ bar: 3, baz: 4 })
  97. render(h(Comp, { qux: 5 }), root)
  98. expect(props).toEqual({})
  99. expect(attrs).toEqual({ qux: 5 })
  100. })
  101. test('functional without declaration', () => {
  102. let props: any
  103. let attrs: any
  104. const Comp: FunctionalComponent = (_props, { attrs: _attrs }) => {
  105. props = _props
  106. attrs = _attrs
  107. }
  108. const root = nodeOps.createElement('div')
  109. render(h(Comp, { foo: 1 }), root)
  110. expect(props).toEqual({ foo: 1 })
  111. expect(attrs).toEqual({ foo: 1 })
  112. expect(props).toBe(attrs)
  113. render(h(Comp, { bar: 2 }), root)
  114. expect(props).toEqual({ bar: 2 })
  115. expect(attrs).toEqual({ bar: 2 })
  116. expect(props).toBe(attrs)
  117. })
  118. test('boolean casting', () => {
  119. let proxy: any
  120. const Comp = {
  121. props: {
  122. foo: Boolean,
  123. bar: Boolean,
  124. baz: Boolean,
  125. qux: Boolean
  126. },
  127. render() {
  128. proxy = this
  129. }
  130. }
  131. render(
  132. h(Comp, {
  133. // absent should cast to false
  134. bar: '', // empty string should cast to true
  135. baz: 'baz', // same string should cast to true
  136. qux: 'ok' // other values should be left in-tact (but raise warning)
  137. }),
  138. nodeOps.createElement('div')
  139. )
  140. expect(proxy.foo).toBe(false)
  141. expect(proxy.bar).toBe(true)
  142. expect(proxy.baz).toBe(true)
  143. expect(proxy.qux).toBe('ok')
  144. expect('type check failed for prop "qux"').toHaveBeenWarned()
  145. })
  146. test('default value', () => {
  147. let proxy: any
  148. const defaultFn = vi.fn(() => ({ a: 1 }))
  149. const defaultBaz = vi.fn(() => ({ b: 1 }))
  150. const Comp = {
  151. props: {
  152. foo: {
  153. default: 1
  154. },
  155. bar: {
  156. default: defaultFn
  157. },
  158. baz: {
  159. type: Function,
  160. default: defaultBaz
  161. }
  162. },
  163. render() {
  164. proxy = this
  165. }
  166. }
  167. const root = nodeOps.createElement('div')
  168. render(h(Comp, { foo: 2 }), root)
  169. expect(proxy.foo).toBe(2)
  170. const prevBar = proxy.bar
  171. expect(proxy.bar).toEqual({ a: 1 })
  172. expect(proxy.baz).toEqual(defaultBaz)
  173. expect(defaultFn).toHaveBeenCalledTimes(1)
  174. expect(defaultBaz).toHaveBeenCalledTimes(0)
  175. // #999: updates should not cause default factory of unchanged prop to be
  176. // called again
  177. render(h(Comp, { foo: 3 }), root)
  178. expect(proxy.foo).toBe(3)
  179. expect(proxy.bar).toEqual({ a: 1 })
  180. expect(proxy.bar).toBe(prevBar)
  181. expect(defaultFn).toHaveBeenCalledTimes(1)
  182. render(h(Comp, { bar: { b: 2 } }), root)
  183. expect(proxy.foo).toBe(1)
  184. expect(proxy.bar).toEqual({ b: 2 })
  185. expect(defaultFn).toHaveBeenCalledTimes(1)
  186. render(h(Comp, { foo: 3, bar: { b: 3 } }), root)
  187. expect(proxy.foo).toBe(3)
  188. expect(proxy.bar).toEqual({ b: 3 })
  189. expect(defaultFn).toHaveBeenCalledTimes(1)
  190. render(h(Comp, { bar: { b: 4 } }), root)
  191. expect(proxy.foo).toBe(1)
  192. expect(proxy.bar).toEqual({ b: 4 })
  193. expect(defaultFn).toHaveBeenCalledTimes(1)
  194. })
  195. test('using inject in default value factory', () => {
  196. const Child = defineComponent({
  197. props: {
  198. test: {
  199. default: () => inject('test', 'default')
  200. }
  201. },
  202. setup(props) {
  203. return () => {
  204. return h('div', props.test)
  205. }
  206. }
  207. })
  208. const Comp = {
  209. setup() {
  210. provide('test', 'injected')
  211. return () => h(Child)
  212. }
  213. }
  214. const root = nodeOps.createElement('div')
  215. render(h(Comp), root)
  216. expect(serializeInner(root)).toBe(`<div>injected</div>`)
  217. })
  218. test('optimized props updates', async () => {
  219. const Child = defineComponent({
  220. props: ['foo'],
  221. template: `<div>{{ foo }}</div>`
  222. })
  223. const foo = ref(1)
  224. const id = ref('a')
  225. const Comp = defineComponent({
  226. setup() {
  227. return {
  228. foo,
  229. id
  230. }
  231. },
  232. components: { Child },
  233. template: `<Child :foo="foo" :id="id"/>`
  234. })
  235. // Note this one is using the main Vue render so it can compile template
  236. // on the fly
  237. const root = document.createElement('div')
  238. domRender(h(Comp), root)
  239. expect(root.innerHTML).toBe('<div id="a">1</div>')
  240. foo.value++
  241. await nextTick()
  242. expect(root.innerHTML).toBe('<div id="a">2</div>')
  243. id.value = 'b'
  244. await nextTick()
  245. expect(root.innerHTML).toBe('<div id="b">2</div>')
  246. })
  247. test('warn props mutation', () => {
  248. let instance: ComponentInternalInstance
  249. let setupProps: any
  250. const Comp = {
  251. props: ['foo'],
  252. setup(props: any) {
  253. instance = getCurrentInstance()!
  254. setupProps = props
  255. return () => null
  256. }
  257. }
  258. render(h(Comp, { foo: 1 }), nodeOps.createElement('div'))
  259. expect(setupProps.foo).toBe(1)
  260. expect(instance!.props.foo).toBe(1)
  261. setupProps.foo = 2
  262. expect(`Set operation on key "foo" failed`).toHaveBeenWarned()
  263. expect(() => {
  264. ;(instance!.proxy as any).foo = 2
  265. }).toThrow(TypeError)
  266. expect(`Attempting to mutate prop "foo"`).toHaveBeenWarned()
  267. // should not throw when overriding properties other than props
  268. expect(() => {
  269. ;(instance!.proxy as any).hasOwnProperty = () => {}
  270. }).not.toThrow(TypeError)
  271. })
  272. test('warn absent required props', () => {
  273. const Comp = {
  274. props: {
  275. bool: { type: Boolean, required: true },
  276. str: { type: String, required: true },
  277. num: { type: Number, required: true }
  278. },
  279. setup() {
  280. return () => null
  281. }
  282. }
  283. render(h(Comp), nodeOps.createElement('div'))
  284. expect(`Missing required prop: "bool"`).toHaveBeenWarned()
  285. expect(`Missing required prop: "str"`).toHaveBeenWarned()
  286. expect(`Missing required prop: "num"`).toHaveBeenWarned()
  287. })
  288. test('warn on type mismatch', () => {
  289. class MyClass {}
  290. const Comp = {
  291. props: {
  292. bool: { type: Boolean },
  293. str: { type: String },
  294. num: { type: Number },
  295. arr: { type: Array },
  296. obj: { type: Object },
  297. cls: { type: MyClass },
  298. fn: { type: Function },
  299. skipCheck: { type: [Boolean, Function], skipCheck: true }
  300. },
  301. setup() {
  302. return () => null
  303. }
  304. }
  305. render(
  306. h(Comp, {
  307. bool: 'true',
  308. str: 100,
  309. num: '100',
  310. arr: {},
  311. obj: 'false',
  312. cls: {},
  313. fn: true,
  314. skipCheck: 'foo'
  315. }),
  316. nodeOps.createElement('div')
  317. )
  318. expect(
  319. `Invalid prop: type check failed for prop "bool". Expected Boolean, got String`
  320. ).toHaveBeenWarned()
  321. expect(
  322. `Invalid prop: type check failed for prop "str". Expected String with value "100", got Number with value 100.`
  323. ).toHaveBeenWarned()
  324. expect(
  325. `Invalid prop: type check failed for prop "num". Expected Number with value 100, got String with value "100".`
  326. ).toHaveBeenWarned()
  327. expect(
  328. `Invalid prop: type check failed for prop "arr". Expected Array, got Object`
  329. ).toHaveBeenWarned()
  330. expect(
  331. `Invalid prop: type check failed for prop "obj". Expected Object, got String with value "false"`
  332. ).toHaveBeenWarned()
  333. expect(
  334. `Invalid prop: type check failed for prop "fn". Expected Function, got Boolean with value true.`
  335. ).toHaveBeenWarned()
  336. expect(
  337. `Invalid prop: type check failed for prop "cls". Expected MyClass, got Object`
  338. ).toHaveBeenWarned()
  339. expect(
  340. `Invalid prop: type check failed for prop "skipCheck". Expected Boolean | Function, got String with value "foo".`
  341. ).not.toHaveBeenWarned()
  342. })
  343. // #3495
  344. test('should not warn required props using kebab-case', async () => {
  345. const Comp = {
  346. props: {
  347. fooBar: { type: String, required: true }
  348. },
  349. setup() {
  350. return () => null
  351. }
  352. }
  353. render(
  354. h(Comp, {
  355. 'foo-bar': 'hello'
  356. }),
  357. nodeOps.createElement('div')
  358. )
  359. expect(`Missing required prop: "fooBar"`).not.toHaveBeenWarned()
  360. })
  361. test('merging props from mixins and extends', () => {
  362. let setupProps: any
  363. let renderProxy: any
  364. const E = {
  365. props: ['base']
  366. }
  367. const M1 = {
  368. props: ['m1']
  369. }
  370. const M2 = {
  371. props: { m2: null }
  372. }
  373. const Comp = {
  374. props: ['self'],
  375. mixins: [M1, M2],
  376. extends: E,
  377. setup(props: any) {
  378. setupProps = props
  379. },
  380. render(this: any) {
  381. renderProxy = this
  382. return h('div', [this.self, this.base, this.m1, this.m2])
  383. }
  384. }
  385. const root = nodeOps.createElement('div')
  386. const props = {
  387. self: 'from self, ',
  388. base: 'from base, ',
  389. m1: 'from mixin 1, ',
  390. m2: 'from mixin 2'
  391. }
  392. render(h(Comp, props), root)
  393. expect(serializeInner(root)).toMatch(
  394. `from self, from base, from mixin 1, from mixin 2`
  395. )
  396. expect(setupProps).toMatchObject(props)
  397. expect(renderProxy.$props).toMatchObject(props)
  398. })
  399. test('merging props from global mixins', () => {
  400. let setupProps: any
  401. let renderProxy: any
  402. const M1 = {
  403. props: ['m1']
  404. }
  405. const M2 = {
  406. props: { m2: null }
  407. }
  408. const Comp = {
  409. props: ['self'],
  410. setup(props: any) {
  411. setupProps = props
  412. },
  413. render(this: any) {
  414. renderProxy = this
  415. return h('div', [this.self, this.m1, this.m2])
  416. }
  417. }
  418. const props = {
  419. self: 'from self, ',
  420. m1: 'from mixin 1, ',
  421. m2: 'from mixin 2'
  422. }
  423. const app = createApp(Comp, props)
  424. app.mixin(M1)
  425. app.mixin(M2)
  426. const root = nodeOps.createElement('div')
  427. app.mount(root)
  428. expect(serializeInner(root)).toMatch(
  429. `from self, from mixin 1, from mixin 2`
  430. )
  431. expect(setupProps).toMatchObject(props)
  432. expect(renderProxy.$props).toMatchObject(props)
  433. })
  434. test('props type support BigInt', () => {
  435. const Comp = {
  436. props: {
  437. foo: BigInt
  438. },
  439. render(this: any) {
  440. return h('div', [this.foo])
  441. }
  442. }
  443. const root = nodeOps.createElement('div')
  444. render(
  445. h(Comp, {
  446. foo: BigInt(BigInt(100000111)) + BigInt(2000000000) * BigInt(30000000)
  447. }),
  448. root
  449. )
  450. expect(serializeInner(root)).toMatch('<div>60000000100000111</div>')
  451. })
  452. // #3474
  453. test('should cache the value returned from the default factory to avoid unnecessary watcher trigger', async () => {
  454. let count = 0
  455. const Comp = {
  456. props: {
  457. foo: {
  458. type: Object,
  459. default: () => ({ val: 1 })
  460. },
  461. bar: Number
  462. },
  463. setup(props: any) {
  464. watch(
  465. () => props.foo,
  466. () => {
  467. count++
  468. }
  469. )
  470. return () => h('h1', [props.foo.val, props.bar])
  471. }
  472. }
  473. const foo = ref()
  474. const bar = ref(0)
  475. const app = createApp({
  476. render: () => h(Comp, { foo: foo.value, bar: bar.value })
  477. })
  478. const root = nodeOps.createElement('div')
  479. app.mount(root)
  480. expect(serializeInner(root)).toMatch(`<h1>10</h1>`)
  481. expect(count).toBe(0)
  482. bar.value++
  483. await nextTick()
  484. expect(serializeInner(root)).toMatch(`<h1>11</h1>`)
  485. expect(count).toBe(0)
  486. })
  487. // #3288
  488. test('declared prop key should be present even if not passed', async () => {
  489. let initialKeys: string[] = []
  490. const changeSpy = vi.fn()
  491. const passFoo = ref(false)
  492. const Comp = {
  493. render() {},
  494. props: {
  495. foo: String
  496. },
  497. setup(props: any) {
  498. initialKeys = Object.keys(props)
  499. const { foo } = toRefs(props)
  500. watch(foo, changeSpy)
  501. }
  502. }
  503. const Parent = () => (passFoo.value ? h(Comp, { foo: 'ok' }) : h(Comp))
  504. const root = nodeOps.createElement('div')
  505. createApp(Parent).mount(root)
  506. expect(initialKeys).toMatchObject(['foo'])
  507. passFoo.value = true
  508. await nextTick()
  509. expect(changeSpy).toHaveBeenCalledTimes(1)
  510. })
  511. // #3371
  512. test(`avoid double-setting props when casting`, async () => {
  513. const Parent = {
  514. setup(props: any, { slots }: SetupContext) {
  515. const childProps = ref()
  516. const registerChildProps = (props: any) => {
  517. childProps.value = props
  518. }
  519. provide('register', registerChildProps)
  520. return () => {
  521. // access the child component's props
  522. childProps.value && childProps.value.foo
  523. return slots.default!()
  524. }
  525. }
  526. }
  527. const Child = {
  528. props: {
  529. foo: {
  530. type: Boolean,
  531. required: false
  532. }
  533. },
  534. setup(props: { foo: boolean }) {
  535. const register = inject('register') as any
  536. // 1. change the reactivity data of the parent component
  537. // 2. register its own props to the parent component
  538. register(props)
  539. return () => 'foo'
  540. }
  541. }
  542. const App = {
  543. setup() {
  544. return () => h(Parent, () => h(Child as any, { foo: '' }, () => null))
  545. }
  546. }
  547. const root = nodeOps.createElement('div')
  548. render(h(App), root)
  549. await nextTick()
  550. expect(serializeInner(root)).toBe(`foo`)
  551. })
  552. test('support null in required + multiple-type declarations', () => {
  553. const Comp = {
  554. props: {
  555. foo: { type: [Function, null], required: true }
  556. },
  557. render() {}
  558. }
  559. const root = nodeOps.createElement('div')
  560. expect(() => {
  561. render(h(Comp, { foo: () => {} }), root)
  562. }).not.toThrow()
  563. expect(() => {
  564. render(h(Comp, { foo: null }), root)
  565. }).not.toThrow()
  566. })
  567. // #5016
  568. test('handling attr with undefined value', () => {
  569. const Comp = {
  570. render(this: any) {
  571. return JSON.stringify(this.$attrs) + Object.keys(this.$attrs)
  572. }
  573. }
  574. const root = nodeOps.createElement('div')
  575. let attrs: any = { foo: undefined }
  576. render(h(Comp, attrs), root)
  577. expect(serializeInner(root)).toBe(
  578. JSON.stringify(attrs) + Object.keys(attrs)
  579. )
  580. render(h(Comp, (attrs = { foo: 'bar' })), root)
  581. expect(serializeInner(root)).toBe(
  582. JSON.stringify(attrs) + Object.keys(attrs)
  583. )
  584. })
  585. // #691ef
  586. test('should not mutate original props long-form definition object', () => {
  587. const props = {
  588. msg: {
  589. type: String
  590. }
  591. }
  592. const Comp = defineComponent({
  593. props,
  594. render() {}
  595. })
  596. const root = nodeOps.createElement('div')
  597. render(h(Comp, { msg: 'test' }), root)
  598. expect(Object.keys(props.msg).length).toBe(1)
  599. })
  600. })