Guest User

Untitled

a guest
May 26th, 2018
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.53 KB | None | 0 0
  1. export default function transformer(file, api) {
  2. const j = api.jscodeshift;
  3. const root = j(file.source);
  4.  
  5. const getClockMocker = j.variableDeclaration('const', [
  6. j.variableDeclarator(
  7. j.identifier('clock'),
  8. j.callExpression(j.identifier('ClockMocker.getClock'), [])
  9. )
  10. ]);
  11.  
  12. const nextClockMocker = j.expressionStatement(j.callExpression(j.identifier('clock.next'), []));
  13.  
  14. const uninstallClockMocker = j.expressionStatement(
  15. j.callExpression(j.identifier('ClockMocker.uninstall'), [])
  16. );
  17.  
  18. const tests = root.find(j.CallExpression, {
  19. callee: {
  20. name: 'it'
  21. }
  22. });
  23.  
  24. tests.forEach(test => {
  25. const blockStatement = test.value.arguments[1].body;
  26. const waitForReactRerenderFunctions = j(blockStatement).find(j.CallExpression, {
  27. callee: {
  28. name: 'waitForReactRerender'
  29. }
  30. });
  31.  
  32. if (waitForReactRerenderFunctions.paths().length > 0) {
  33. // remove waitForReactRerender import
  34. root
  35. .find(j.ImportDefaultSpecifier, { local: { name: 'waitForReactRerender' } })
  36. .forEach(path => j(path.parentPath.parentPath).remove());
  37.  
  38. // add ClockMocker import if needed
  39. if (root.find(j.ImportDefaultSpecifier, { local: { name: 'ClockMocker' } }).length === 0) {
  40. const cmImport = j.importDeclaration(
  41. [j.importDefaultSpecifier(j.identifier('ClockMocker'))],
  42. j.literal('test/testUtilities/ClockMocker')
  43. );
  44. root
  45. .find(j.Program)
  46. .get('body')
  47. .get(0)
  48. .insertBefore(cmImport);
  49. }
  50.  
  51. const blockBody = j(blockStatement).get('body');
  52. blockBody.get(0).insertBefore(getClockMocker);
  53.  
  54. blockBody.get(blockBody.value.length - 1).insertAfter(uninstallClockMocker);
  55.  
  56. //make test sync
  57. j(test)
  58. .find(j.Identifier, { name: 'done' })
  59. .remove();
  60. }
  61. let FunctionContents = new Map();
  62. waitForReactRerenderFunctions.forEach(path => {
  63. // add clock.next(); to the beginning of each function
  64. j(path.value.arguments).forEach(arg => {
  65. const funcBody = j(arg).get('body');
  66. if (funcBody.value) {
  67. const existingValue = FunctionContents.get(path.parentPath) || [];
  68. FunctionContents.set(path.parentPath, [
  69. ...existingValue,
  70. nextClockMocker,
  71. ...funcBody.value.body
  72. ]);
  73. }
  74. });
  75. });
  76. FunctionContents.forEach((values, key) =>
  77. values.reverse().forEach(value => key.insertAfter(value))
  78. );
  79. waitForReactRerenderFunctions.remove();
  80. });
  81.  
  82. return root.toSource();
  83. }
Add Comment
Please, Sign In to add comment