In React components importing assets (ex, import logo from "../../../assets/img/logo.png) gives such error
({"Object.":function(module,exports,require,__dirname,__filename,global,jest){�PNG
SyntaxError: Invalid or unexpected token at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:305:17)
my jest config is
"jest": {
"testRegex": ".*\\.spec\\.js$",
"moduleFileExtensions": [
"js",
"jsx",
"json"
],
"moduleDirectories": [
"node_modules",
"src",
"assets"
],
"moduleNameMapper": {
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$/": "<rootDir>/__mocks__/fileMock.js",
"\\.(css|less|scss)$": "<rootDir>/__mocks__/styleMock.js"
},
"verbose": true,
"bail": true
}
what am i missing?
When you import image files, Jest tries to interpret the binary codes of the images as .js, hence runs into errors.
The only way out is to mock a default response anytime jest sees an image import!
"jest": {
"moduleNameMapper": {
"\\.(jpg|ico|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/mocks/fileMock.js",
"\\.(css|less)$": "<rootDir>/mocks/fileMock.js"
}
}
Note: if you already have the "Jest"
key, just add the "moduleNameMapper"
child in it
mocks
folder in your root and create fileMock.js
file inside it. populate the file with the snippet belowmodule.exports = '';
Note: If you are using es6 you can use export default '';
to avoid an Eslint flag
when you are done with the above steps, you can restart the test and you are good to go.
Note. remember to add the varying extensions of your image files in the moduleNameMapper
so that they can be mocked.
I hope I have been able to help. #cheers!
For anyone looking into this problem. You have to do install npm install --save-dev identity-obj-proxy
to get the necessary dependencies.
"jest": {
"moduleNameMapper": {
".+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$": "identity-obj-proxy"
}
}
I had the same problem and I solved it as follows:
npm install -D jest-transform-stub
"jest": {
...
"transform": {
...
".+\\.(css|scss|png|jpg|svg)$": "jest-transform-stub"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With