Skip to content

Commit

Permalink
Fix issue with jest caching of block.json files (#16899)
Browse files Browse the repository at this point in the history
* Generate cache key for block index files by concatenating the index with the block json file

* Move implementation to the test/unit folder
  • Loading branch information
talldan authored Aug 6, 2019
1 parent 4ef60f3 commit 1ecb543
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
3 changes: 3 additions & 0 deletions test/unit/jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,7 @@ module.exports = {
'<rootDir>/.*/build-module/',
'<rootDir>/.+\.native\.js$',
],
transform: {
'^.+\\.[jt]sx?$': '<rootDir>/test/unit/scripts/babel-transformer.js',
},
};
40 changes: 40 additions & 0 deletions test/unit/scripts/babel-transformer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
const fs = require( 'fs' );
const babelJest = require( 'babel-jest' );
const babelJestTransformer = babelJest.createTransformer();

module.exports = {
// This transformer extends the babel-jest transformer.
...babelJestTransformer,

/**
* A cache key generator that extends babel-jest's cache key generator,
* but adds some additional handling for invalidating the cache when a
* change to a block.json file is made.
*
* @param {string} src The source of the file being transformed.
* @param {string} filename The filename of the file being transformed.
* @param {...any} args Any other args passed to the function.
*
* @return {string} The cache key for the file.
*/
getCacheKey( src, filename, ...args ) {
const isBlockIndex = /block-library[\/\\]src[\/\\].+[\/\\]index\.js/.test( filename );

if ( ! isBlockIndex ) {
return babelJestTransformer.getCacheKey( src, filename, ...args );
}

const blockJSONFilename = filename.replace( 'index.js', 'block.json' );

if ( ! fs.existsSync( blockJSONFilename ) ) {
return babelJestTransformer.getCacheKey( src, filename, ...args );
}

// If the file is a block index file and there's a block json file, generate the
// jest cache key for this file by concatenating the block index and block json
// src together. This will result in the cache key changing and the cache being
// invalidated for the index when any changes to the json are made.
const blockJSONSrc = fs.readFileSync( blockJSONFilename );
return babelJestTransformer.getCacheKey( `${ src }\n${ blockJSONSrc }`, filename, ...args );
},
};

0 comments on commit 1ecb543

Please sign in to comment.