testUtils.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. /**
  2. * Copyright (c) Facebook, Inc. and its affiliates.
  3. *
  4. * This source code is licensed under the MIT license found in the
  5. * LICENSE file in the root directory of this source tree.
  6. */
  7. 'use strict';
  8. const fs = require('fs');
  9. const mkdirp = require('mkdirp');
  10. const path = require('path');
  11. const temp = require('temp');
  12. function renameFileTo(oldPath, newFilename) {
  13. const projectPath = path.dirname(oldPath);
  14. const newPath = path.join(projectPath, newFilename);
  15. mkdirp.sync(path.dirname(newPath));
  16. fs.renameSync(oldPath, newPath);
  17. return newPath;
  18. }
  19. function createTempFileWith(content, filename, extension) {
  20. const info = temp.openSync({ suffix: extension });
  21. let filePath = info.path;
  22. fs.writeSync(info.fd, content);
  23. fs.closeSync(info.fd);
  24. if (filename) {
  25. filePath = renameFileTo(filePath, filename);
  26. }
  27. return filePath;
  28. }
  29. exports.createTempFileWith = createTempFileWith;
  30. // Test transform files need a js extension to work with @babel/register
  31. // .ts or .tsx work as well
  32. function createTransformWith(content, ext='.js') {
  33. return createTempFileWith(
  34. 'module.exports = function(fileInfo, api, options) { ' + content + ' }',
  35. undefined,
  36. ext
  37. );
  38. }
  39. exports.createTransformWith = createTransformWith;
  40. function getFileContent(filePath) {
  41. return fs.readFileSync(filePath).toString();
  42. }
  43. exports.getFileContent = getFileContent;