componentProps.spec.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672
  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. },
  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. }),
  314. nodeOps.createElement('div')
  315. )
  316. expect(
  317. `Invalid prop: type check failed for prop "bool". Expected Boolean, got String`
  318. ).toHaveBeenWarned()
  319. expect(
  320. `Invalid prop: type check failed for prop "str". Expected String with value "100", got Number with value 100.`
  321. ).toHaveBeenWarned()
  322. expect(
  323. `Invalid prop: type check failed for prop "num". Expected Number with value 100, got String with value "100".`
  324. ).toHaveBeenWarned()
  325. expect(
  326. `Invalid prop: type check failed for prop "arr". Expected Array, got Object`
  327. ).toHaveBeenWarned()
  328. expect(
  329. `Invalid prop: type check failed for prop "obj". Expected Object, got String with value "false"`
  330. ).toHaveBeenWarned()
  331. expect(
  332. `Invalid prop: type check failed for prop "fn". Expected Function, got Boolean with value true.`
  333. ).toHaveBeenWarned()
  334. expect(
  335. `Invalid prop: type check failed for prop "cls". Expected MyClass, got Object`
  336. ).toHaveBeenWarned()
  337. })
  338. // #3495
  339. test('should not warn required props using kebab-case', async () => {
  340. const Comp = {
  341. props: {
  342. fooBar: { type: String, required: true }
  343. },
  344. setup() {
  345. return () => null
  346. }
  347. }
  348. render(
  349. h(Comp, {
  350. 'foo-bar': 'hello'
  351. }),
  352. nodeOps.createElement('div')
  353. )
  354. expect(`Missing required prop: "fooBar"`).not.toHaveBeenWarned()
  355. })
  356. test('merging props from mixins and extends', () => {
  357. let setupProps: any
  358. let renderProxy: any
  359. const E = {
  360. props: ['base']
  361. }
  362. const M1 = {
  363. props: ['m1']
  364. }
  365. const M2 = {
  366. props: { m2: null }
  367. }
  368. const Comp = {
  369. props: ['self'],
  370. mixins: [M1, M2],
  371. extends: E,
  372. setup(props: any) {
  373. setupProps = props
  374. },
  375. render(this: any) {
  376. renderProxy = this
  377. return h('div', [this.self, this.base, this.m1, this.m2])
  378. }
  379. }
  380. const root = nodeOps.createElement('div')
  381. const props = {
  382. self: 'from self, ',
  383. base: 'from base, ',
  384. m1: 'from mixin 1, ',
  385. m2: 'from mixin 2'
  386. }
  387. render(h(Comp, props), root)
  388. expect(serializeInner(root)).toMatch(
  389. `from self, from base, from mixin 1, from mixin 2`
  390. )
  391. expect(setupProps).toMatchObject(props)
  392. expect(renderProxy.$props).toMatchObject(props)
  393. })
  394. test('merging props from global mixins', () => {
  395. let setupProps: any
  396. let renderProxy: any
  397. const M1 = {
  398. props: ['m1']
  399. }
  400. const M2 = {
  401. props: { m2: null }
  402. }
  403. const Comp = {
  404. props: ['self'],
  405. setup(props: any) {
  406. setupProps = props
  407. },
  408. render(this: any) {
  409. renderProxy = this
  410. return h('div', [this.self, this.m1, this.m2])
  411. }
  412. }
  413. const props = {
  414. self: 'from self, ',
  415. m1: 'from mixin 1, ',
  416. m2: 'from mixin 2'
  417. }
  418. const app = createApp(Comp, props)
  419. app.mixin(M1)
  420. app.mixin(M2)
  421. const root = nodeOps.createElement('div')
  422. app.mount(root)
  423. expect(serializeInner(root)).toMatch(
  424. `from self, from mixin 1, from mixin 2`
  425. )
  426. expect(setupProps).toMatchObject(props)
  427. expect(renderProxy.$props).toMatchObject(props)
  428. })
  429. test('props type support BigInt', () => {
  430. const Comp = {
  431. props: {
  432. foo: BigInt
  433. },
  434. render(this: any) {
  435. return h('div', [this.foo])
  436. }
  437. }
  438. const root = nodeOps.createElement('div')
  439. render(
  440. h(Comp, {
  441. foo: BigInt(BigInt(100000111)) + BigInt(2000000000) * BigInt(30000000)
  442. }),
  443. root
  444. )
  445. expect(serializeInner(root)).toMatch('<div>60000000100000111</div>')
  446. })
  447. // #3474
  448. test('should cache the value returned from the default factory to avoid unnecessary watcher trigger', async () => {
  449. let count = 0
  450. const Comp = {
  451. props: {
  452. foo: {
  453. type: Object,
  454. default: () => ({ val: 1 })
  455. },
  456. bar: Number
  457. },
  458. setup(props: any) {
  459. watch(
  460. () => props.foo,
  461. () => {
  462. count++
  463. }
  464. )
  465. return () => h('h1', [props.foo.val, props.bar])
  466. }
  467. }
  468. const foo = ref()
  469. const bar = ref(0)
  470. const app = createApp({
  471. render: () => h(Comp, { foo: foo.value, bar: bar.value })
  472. })
  473. const root = nodeOps.createElement('div')
  474. app.mount(root)
  475. expect(serializeInner(root)).toMatch(`<h1>10</h1>`)
  476. expect(count).toBe(0)
  477. bar.value++
  478. await nextTick()
  479. expect(serializeInner(root)).toMatch(`<h1>11</h1>`)
  480. expect(count).toBe(0)
  481. })
  482. // #3288
  483. test('declared prop key should be present even if not passed', async () => {
  484. let initialKeys: string[] = []
  485. const changeSpy = vi.fn()
  486. const passFoo = ref(false)
  487. const Comp = {
  488. render() {},
  489. props: {
  490. foo: String
  491. },
  492. setup(props: any) {
  493. initialKeys = Object.keys(props)
  494. const { foo } = toRefs(props)
  495. watch(foo, changeSpy)
  496. }
  497. }
  498. const Parent = () => (passFoo.value ? h(Comp, { foo: 'ok' }) : h(Comp))
  499. const root = nodeOps.createElement('div')
  500. createApp(Parent).mount(root)
  501. expect(initialKeys).toMatchObject(['foo'])
  502. passFoo.value = true
  503. await nextTick()
  504. expect(changeSpy).toHaveBeenCalledTimes(1)
  505. })
  506. // #3371
  507. test(`avoid double-setting props when casting`, async () => {
  508. const Parent = {
  509. setup(props: any, { slots }: SetupContext) {
  510. const childProps = ref()
  511. const registerChildProps = (props: any) => {
  512. childProps.value = props
  513. }
  514. provide('register', registerChildProps)
  515. return () => {
  516. // access the child component's props
  517. childProps.value && childProps.value.foo
  518. return slots.default!()
  519. }
  520. }
  521. }
  522. const Child = {
  523. props: {
  524. foo: {
  525. type: Boolean,
  526. required: false
  527. }
  528. },
  529. setup(props: { foo: boolean }) {
  530. const register = inject('register') as any
  531. // 1. change the reactivity data of the parent component
  532. // 2. register its own props to the parent component
  533. register(props)
  534. return () => 'foo'
  535. }
  536. }
  537. const App = {
  538. setup() {
  539. return () => h(Parent, () => h(Child as any, { foo: '' }, () => null))
  540. }
  541. }
  542. const root = nodeOps.createElement('div')
  543. render(h(App), root)
  544. await nextTick()
  545. expect(serializeInner(root)).toBe(`foo`)
  546. })
  547. test('support null in required + multiple-type declarations', () => {
  548. const Comp = {
  549. props: {
  550. foo: { type: [Function, null], required: true }
  551. },
  552. render() {}
  553. }
  554. const root = nodeOps.createElement('div')
  555. expect(() => {
  556. render(h(Comp, { foo: () => {} }), root)
  557. }).not.toThrow()
  558. expect(() => {
  559. render(h(Comp, { foo: null }), root)
  560. }).not.toThrow()
  561. })
  562. // #5016
  563. test('handling attr with undefined value', () => {
  564. const Comp = {
  565. render(this: any) {
  566. return JSON.stringify(this.$attrs) + Object.keys(this.$attrs)
  567. }
  568. }
  569. const root = nodeOps.createElement('div')
  570. let attrs: any = { foo: undefined }
  571. render(h(Comp, attrs), root)
  572. expect(serializeInner(root)).toBe(
  573. JSON.stringify(attrs) + Object.keys(attrs)
  574. )
  575. render(h(Comp, (attrs = { foo: 'bar' })), root)
  576. expect(serializeInner(root)).toBe(
  577. JSON.stringify(attrs) + Object.keys(attrs)
  578. )
  579. })
  580. // #691ef
  581. test('should not mutate original props long-form definition object', () => {
  582. const props = {
  583. msg: {
  584. type: String
  585. }
  586. }
  587. const Comp = defineComponent({
  588. props,
  589. render() {}
  590. })
  591. const root = nodeOps.createElement('div')
  592. render(h(Comp, { msg: 'test' }), root)
  593. expect(Object.keys(props.msg).length).toBe(1)
  594. })
  595. })