JSXAttributeMock.js 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. /**
  2. * @flow
  3. */
  4. import toAST from 'to-ast'; // eslint-disable-line import/no-extraneous-dependencies
  5. import JSXExpressionContainerMock from './JSXExpressionContainerMock';
  6. export type JSXAttributeMockType = {
  7. type: 'JSXAttribute',
  8. name: {
  9. type: 'JSXIdentifier',
  10. name: string,
  11. },
  12. value: mixed,
  13. };
  14. export default function JSXAttributeMock(prop: string, value: mixed, isExpressionContainer?: boolean = false): JSXAttributeMockType {
  15. let astValue;
  16. if (value && value.type !== undefined) {
  17. astValue = value;
  18. } else {
  19. astValue = toAST(value);
  20. }
  21. let attributeValue = astValue;
  22. if (isExpressionContainer || astValue.type !== 'Literal') {
  23. attributeValue = JSXExpressionContainerMock(astValue);
  24. } else if (attributeValue.type === 'Literal' && !('raw' in (attributeValue: any))) {
  25. (attributeValue: any).raw = JSON.stringify((attributeValue: any).value);
  26. }
  27. return {
  28. type: 'JSXAttribute',
  29. name: {
  30. type: 'JSXIdentifier',
  31. name: prop,
  32. },
  33. value: attributeValue,
  34. };
  35. }