jeudi 11 mars 2021

How to tell what kind of import did Jest moduleNameMapper mapped?

Is there a way to tell what kind of import the code used before it was being mapped?

In our react project, we use inline require() imports for dynamic image assets (inside of a component) and ES6 imports for static pictures (outside of it). The problem is with testing and particularly with mocking.

When I use mocks for require() to return {default: "i-dont-really-care"}, tests fail for import as they expect string "i-dont-really-care". Is there some kind of a global variable that jest sends along with mapping, that would tell me "I am mapping this and that from this and that source"?

// jest.config.js:

module.exports = {
  moduleNameMapper: {
    '\\.(jpg|ico|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$':
      '<rootDir>tests/js/__mocks__/requireImages.js',
  },
}


// requireImages.js nowadays:

module.exports = { default: '' };


// requireImages.js in a perfect world:

/* global jestInfoOnTheMapping */

const mock = (jestInfoOnTheMapping) => {
  if(jestInfoOnTheMapping.mappedLine.test(/require/g)){
    return { default: 'i-dont-really-care' };
  }

  return 'i-dont-really-care';
};

module.exports = mock(jestInfoOnTheMapping);

Aucun commentaire:

Enregistrer un commentaire