How Can I Manually Mock Svg's in my Tests?
Thanks to Jest's transformenter link description here 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')