componentProps.spec.ts 17 KB

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