Search code examples
reactjsmockingjestjs

How Can I Manually Mock Svg's in my Tests?


I'm using a stub file to mock images in my application, which works 99% of the time for me. However, I have a component that will render different images based on input, so I want to be able to check in my unit tests that the input creates the correct output.

Basically what I'm looking to do is if the user inputs "Lion", my component will display a picture of a lion, "Tiger a tiger, etc. Using moduleNameMapper, it's always test-file-stub and I want to be able to jest.mock('../lion.svg', ()=> 'lion.svg') for specific tests.


Solution

  • Thanks to Jest's transform config setting you may do that.

    package.json

    "jest": {
      "transform": {
        "\\.svg$": "<rootDir>/fileTransformer.js"
      }
      ...
    }
    

    IMPORTANT

    You need to explicitly provide transform to other extensions (especially *.js and *.jsx) otherwise you will get errors. So it should be something like:

    "transform": {
      "^.+\\.js$": "babel-jest",
      "\\.svg$": "<rootDir>/fileTransformer.js"
       ...
    }
    

    As for fileTransformer.js it just emulates exporting file's path(you may add any transformation to strip the path or extension or whatever):

    const path = require('path');
    
    module.exports = {
      process(src, filename) {
        return `module.exports = ${JSON.stringify(path.basename(filename))};`;
      }
    };
    

    It means

    import svgIcon from './moon.svg';
    

    will work just like

    const svgIcon = 'moon.svg'
    

    So for component containing

    ...
      <img src={svgIcon} />
    

    you may write assertion like

    expect(imgElementYouMayFind.props.src)
      .toEqual('moon.svg')