Home Reference Source Test Repository

src/helpers.js

  1. import { parse } from "path"
  2. import lowerCamelCase from "camelcase"
  3. import upperCamelCase from "uppercamelcase"
  4. import { types as t } from "babel-core"
  5.  
  6. export function getModuleName(filename) {
  7. const name = parse(filename).name
  8. return name[0] === name[0].toUpperCase() ? upperCamelCase(name) : lowerCamelCase(name)
  9. }
  10.  
  11. export function ensureIdentifier(value) {
  12. return typeof value === "string" ? t.identifier(value) : value
  13. }
  14.  
  15. export function ensureStringLiteral(value) {
  16. return typeof value === "string" ? t.stringLiteral(value) : value
  17. }
  18.  
  19. export function buildMockExportDefaultDeclaration(mock, name, expression) {
  20. return t.exportDefaultDeclaration(t.callExpression(
  21. ensureIdentifier(mock), [ ensureIdentifier(expression), ensureStringLiteral(name) ]
  22. ))
  23. }
  24.  
  25. export function buildMockExportVar(mock, name, _name, declaration) {
  26. return t.variableDeclaration("const",
  27. [
  28. t.variableDeclarator(
  29. ensureIdentifier(_name),
  30. t.callExpression(
  31. ensureIdentifier(mock),
  32. [ ensureIdentifier(declaration || name), ensureStringLiteral(name) ]
  33. )
  34. ),
  35. ]
  36. )
  37. }
  38.  
  39. export function buildExportNamedDeclaration(local, exported) {
  40. return t.exportNamedDeclaration(
  41. null,
  42. [
  43. t.exportSpecifier(ensureIdentifier(local), ensureIdentifier(exported)),
  44. ],
  45. null
  46. )
  47. }
  48.  
  49. export function buildMocktailImport(mock) {
  50. return t.importDeclaration(
  51. [ t.importSpecifier(mock, ensureIdentifier("mock")) ],
  52. ensureStringLiteral("mocktail")
  53. )
  54. }