componentProps.spec.ts 16 KB

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