Yatrix
Yatrix

Reputation: 13775

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.

Upvotes: 12

Views: 28501

Answers (3)

tallpaul
tallpaul

Reputation: 1513

Small update to the above answers since Jest v28 introduced breaking changes:

const path = require("path");

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

Updated documentation

Upvotes: 1

skyboyer
skyboyer

Reputation: 23705

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')

Upvotes: 19

Pavel Ivanov
Pavel Ivanov

Reputation: 19

Just a small addition to what @skyboyer suggest:

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

instead you need have it like that:

module.exports = {
  process(filename) {
    return `module.exports =  ${JSON.stringify(path.basename(filename))};`;
  }
};

pay attention to ; after closing curly bracket.

Upvotes: 2

Related Questions