jest-preview icon indicating copy to clipboard operation
jest-preview copied to clipboard

Implement `getCacheKey`

Open nvh95 opened this issue 3 years ago • 3 comments

What & Why

  • Now, jest-preview hasn't implemented getCacheKey for css, file and fileCRA transformer. https://github.com/nvh95/jest-preview/blob/6ce35ca37d6c9de5fc72b05ce433cb83b10b0538/src/preconfigTransform/css.ts#L1-L8
  • The reason is that we are not very deeply understand the benefit of getCacheKey. The [docs]((https://jestjs.io/docs/code-transformation) itself is not very detail. But we know it boosts the performance when running Jest since we're caching the transformed files.

How

  • We can find @swc/jest implemented getCacheKey. Let's see how they do that. https://github.com/swc-project/jest/blob/17cf883b46c050a485975d8ce96a05277cf6032f/index.ts#L37-L52
  • There are some related PRs as well https://github.com/swc-project/jest/pull/32 https://github.com/swc-project/jest/pull/76
  • We need to benchmark to see how much users' time getCacheKey saves.

nvh95 avatar Apr 16 '22 15:04 nvh95

As I observe and guess, if we do not implement getCacheKey, Jest automatically cache using return value in the transformation. For e.g: If our css transform a css file to

const relativeCssPath = "/demo/App.css";
const link = document.createElement('link');
link.rel = 'stylesheet';
link.href = relativeCssPath;
document.body.appendChild(link);

module.exports = JSON.stringify(relativeCssPath);

This whole file content will be used as the key for caching. So what is the point of implementing getCacheKey? To get a shorter key? Do we need to do that?

nvh95 avatar Apr 16 '22 18:04 nvh95

How to see the cache key by yourself

  1. Run jest --clearCache to see where the cache located. For e.g, on mac: /private/var/folders/hg/cg39z3hd4gv3grbrd08524gh0000gp/T/jest_dy
  2. cd to that project and explore
Jest Cache

nvh95 avatar Apr 16 '22 18:04 nvh95

My hypothesis: If we do not explicitly implement getCacheKey. It will use src and filename as cache key.

So, we should add transformer file content into account. So each time we upgrade the transformer. The Jest cache get cleared.

nvh95 avatar Aug 20 '22 16:08 nvh95