testUtils.ts 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import {
  2. NodeTypes,
  3. ElementNode,
  4. locStub,
  5. Namespaces,
  6. ElementTypes,
  7. VNodeCall
  8. } from '../src'
  9. import { isString, PatchFlags, PatchFlagNames, isArray } from '@vue/shared'
  10. const leadingBracketRE = /^\[/
  11. const bracketsRE = /^\[|\]$/g
  12. // Create a matcher for an object
  13. // where non-static expressions should be wrapped in []
  14. // e.g.
  15. // - createObjectMatcher({ 'foo': '[bar]' }) matches { foo: bar }
  16. // - createObjectMatcher({ '[foo]': 'bar' }) matches { [foo]: "bar" }
  17. export function createObjectMatcher(obj: Record<string, any>) {
  18. return {
  19. type: NodeTypes.JS_OBJECT_EXPRESSION,
  20. properties: Object.keys(obj).map(key => ({
  21. type: NodeTypes.JS_PROPERTY,
  22. key: {
  23. type: NodeTypes.SIMPLE_EXPRESSION,
  24. content: key.replace(bracketsRE, ''),
  25. isStatic: !leadingBracketRE.test(key)
  26. },
  27. value: isString(obj[key])
  28. ? {
  29. type: NodeTypes.SIMPLE_EXPRESSION,
  30. content: obj[key].replace(bracketsRE, ''),
  31. isStatic: !leadingBracketRE.test(obj[key])
  32. }
  33. : obj[key]
  34. }))
  35. }
  36. }
  37. export function createElementWithCodegen(
  38. tag: VNodeCall['tag'],
  39. props?: VNodeCall['props'],
  40. children?: VNodeCall['children'],
  41. patchFlag?: VNodeCall['patchFlag'],
  42. dynamicProps?: VNodeCall['dynamicProps']
  43. ): ElementNode {
  44. return {
  45. type: NodeTypes.ELEMENT,
  46. loc: locStub,
  47. ns: Namespaces.HTML,
  48. tag: 'div',
  49. tagType: ElementTypes.ELEMENT,
  50. isSelfClosing: false,
  51. props: [],
  52. children: [],
  53. codegenNode: {
  54. type: NodeTypes.VNODE_CALL,
  55. tag,
  56. props,
  57. children,
  58. patchFlag,
  59. dynamicProps,
  60. directives: undefined,
  61. isBlock: false,
  62. disableTracking: false,
  63. loc: locStub
  64. }
  65. }
  66. }
  67. export function genFlagText(flag: PatchFlags | PatchFlags[]) {
  68. if (isArray(flag)) {
  69. let f = 0
  70. flag.forEach(ff => {
  71. f |= ff
  72. })
  73. return `${f} /* ${flag.map(f => PatchFlagNames[f]).join(', ')} */`
  74. } else {
  75. return `${flag} /* ${PatchFlagNames[flag]} */`
  76. }
  77. }