cache.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import fs from "fs";
  2. import path from "path";
  3. const testCacheFilename = path.join(__dirname, ".babel");
  4. const oldBabelDisableCacheValue = process.env.BABEL_DISABLE_CACHE;
  5. process.env.BABEL_CACHE_PATH = testCacheFilename;
  6. delete process.env.BABEL_DISABLE_CACHE;
  7. function writeCache(data) {
  8. if (typeof data === "object") {
  9. data = JSON.stringify(data);
  10. }
  11. fs.writeFileSync(testCacheFilename, data);
  12. }
  13. function cleanCache() {
  14. try {
  15. fs.unlinkSync(testCacheFilename);
  16. } catch (e) {
  17. // It is convenient to always try to clear
  18. }
  19. }
  20. function resetCache() {
  21. process.env.BABEL_CACHE_PATH = null;
  22. process.env.BABEL_DISABLE_CACHE = oldBabelDisableCacheValue;
  23. }
  24. describe("@babel/register - caching", () => {
  25. describe("cache", () => {
  26. let load, get, save;
  27. beforeEach(() => {
  28. // Since lib/cache is a singleton we need to fully reload it
  29. jest.resetModules();
  30. const cache = require("../lib/cache");
  31. load = cache.load;
  32. get = cache.get;
  33. save = cache.save;
  34. });
  35. afterEach(cleanCache);
  36. afterAll(resetCache);
  37. it("should load and get cached data", () => {
  38. writeCache({ foo: "bar" });
  39. load();
  40. expect(get()).toEqual({ foo: "bar" });
  41. });
  42. it("should load and get an object with no cached data", () => {
  43. load();
  44. expect(get()).toEqual({});
  45. });
  46. it("should load and get an object with invalid cached data", () => {
  47. writeCache("foobar");
  48. load();
  49. expect(get()).toEqual({});
  50. });
  51. it("should create the cache on save", () => {
  52. save();
  53. expect(fs.existsSync(testCacheFilename)).toBe(true);
  54. expect(get()).toEqual({});
  55. });
  56. });
  57. });