jest: "Syntax Error: Invalid or unexpected token" with .png

I’m trying to test a simple module, but I’m getting this error:

Test suite failed to run

    /home/matheusml/Projects/react-completo/src/assets/images/dribble-logo.png:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){�PNG
                                                                                             ^
    SyntaxError: Invalid or unexpected token
      
      at transformAndBuildScript (node_modules/jest-runtime/build/transform.js:320:12)
      at Object.<anonymous> (src/components/container/Container.js:4:46)
      at Object.<anonymous> (src/components/App.js:4:44)

This is the test:

import React from 'react';
import renderer from 'react-test-renderer';
import { Router } from 'react-router';

import App from './App';

test('App', () => {
  const component = renderer.create(
    <App />
  );
  let tree = component.toJSON();
  expect(tree).toMatchSnapshot();
});

This is my package.json:

"jest": {
    "moduleNameMapper": {
      "\\.(jpg|jpeg|png|svg)$": "./src/config/fileMock.js",
      "\\.(css|scss)$": "identity-obj-proxy"
    }
  }

And this is the fileMock.js:

module.exports = 'test-file-stub';

Thanks!

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Reactions: 84
  • Comments: 36 (5 by maintainers)

Commits related to this issue

Most upvoted comments

I had the same error and resolved it by creating a assetsTransformer.js:

const path = require('path');

module.exports = {
  process(src, filename, config, options) {
    return 'module.exports = ' + JSON.stringify(path.basename(filename)) + ';';
  },
};

Then add this to your jest configuration in package.json: "jest": { "moduleNameMapper": { "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/assetsTransformer.js", "\\.(css|less)$": "<rootDir>/assetsTransformer.js" } },

Source: https://facebook.github.io/jest/docs/webpack.html#content

For anyone looking into this issue @timgivois way works beautifully for me. 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 also seem to be having this issue as well. It only happens when I require the png.

({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){�PNG
                                                                                             ^
    SyntaxError: Invalid or unexpected token

Another workaround:

npm i --save-dev jest-transform-stub
"jest": {
  "transform": {
    ".+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$": "jest-transform-stub"
  }
}

I was having issues with a svg file. I realized I could mock it with identity-obj-proxy:

    "moduleNameMapper": {
      "\\.(css|scss|svg)$": "identity-obj-proxy"
    },

I am dumb, i had another jest.config.js in my root folder which overwrote the settings in package.json. Although it’s not runnning yet, i don’t get this particular error anymore.

Same type error

SyntaxError: Unexpected token <
      /media/sibin/F_WORK/<path>/<icon-name>.svg:1
      ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){<?xml version="1.0" encoding="UTF-8"?>
                                                                                               ^
      SyntaxError: Unexpected token <

Got it working. Here are the important bits (please note that i have some additional config due to enzyme 3 with react 16):

.babelrc

{
  "presets": [
    "es2015",
    "react",
    "stage-1",
    "env"

  ],
  "plugins": [
    "react-hot-loader/babel",
    "transform-class-properties",
    "transform-react-jsx-source",
    "glamorous-displayname",
    "wildcard"
  ],
  "env": {
    "development": {
      "plugins": [
        ["transform-runtime", {
          "polyfill": true
        }]
      ]
    }
  }
}

jest.config.js

// this helps: https://github.com/facebook/jest/issues/2081#issuecomment-332406033
module.exports = {
  verbose: true,
  setupFiles: ['./jest.setup.js'],
  snapshotSerializers: ['jest-glamor-react', 'enzyme-to-json/serializer'],
  moduleFileExtensions: ['js', 'jsx'],
  transform: {
    '^.+\\.jsx?$': 'babel-jest',
    '\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$':
      '<rootDir>/config/jest/assetsTransformer.js',
  },
};

jest.setup.js

import 'raf/polyfill';
import Enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

Enzyme.configure({ adapter: new Adapter() });

Hope that helps someone.

@magnusart

"jest": {
    "moduleNameMapper": {
      ".+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$": "identity-obj-proxy"
    }
  }

it saves my day. Thanks!!.

@magnusart

"jest": {
    "moduleNameMapper": {
      ".+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$": "identity-obj-proxy"
    }
  }

it saves my day. Thanks!!.

I took a cue from this and installed babel-jest then I replace identity-obj-proxy with babel-jest

I was experiencing this on React Native as well, when attempting to jest test a file with React Navigation v5 Stack.Navigator and Stack.Screens in it.

● Test suite failed to run

    E:\my\working\directory\myproject\node_modules\@react-navigation\stack\lib\commonjs\views\assets\back-icon.png:1
    �PNG


    SyntaxError: Invalid or unexpected token
        at compileFunction (<anonymous>)

      at Runtime._execModule (node_modules/jest-runtime/build/index.js:1157:58)
      at Object.<anonymous> (node_modules/@react-navigation/stack/lib/commonjs/index.tsx:13:3)

This is on React Native 0.63.3 with the following installed in the project dependencies.

"@babel/core": "7.8.4",
"@babel/runtime": "7.8.4",
...
"babel-jest": "25.1.0",
"babel-loader": "^8.1.0",
"babel-plugin-module-resolver": "4.0.0",
...
"jest": "25.1.0",
"metro-react-native-babel-preset": "0.59.0",

What fixed this for me was:

  1. Installing "jest-transform-stub": "2.0.0"
  2. Modifying my jest.config.js file by adding this to the module.exports object:
  transform: {
    '.+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$': 'jest-transform-stub',
  },
  moduleNameMapper: {
    '^.+.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$': 'jest-transform-stub',
  },

I believe in my case the moduleNameMapper was the only one really needed, but I’m keeping both for now as it works. Hopefully this may help another that runs into this.

Same error as well. Does someone fix it?

In my case, I didn’t realize that <rootDir> is a token supplied by Jest, and assumed it was something I needed to replace. Adding it to the moduleNameMapper entries solved the issue.

I solved this by using the jest-react-native package, as all solutions here did not work out for me. Maybe my problem is a different one, because I got problems with PNG files sitting inside the react-native-router-flux-package.

Here some fragment of my package.json file:

{
  // ... 
  "devDependencies": {
    // ...
    "jest": "^23.4.1",
    "jest-react-native": "^18.0.0",
  },
  "jest": {
    "preset": "jest-react-native",
    "verbose": true,
    "modulePathIgnorePatterns": [
      "<rootDir>/node_modules/react-native/Libraries/react-native/",
      "<rootDir>/node_modules/react-native/packager/"
    ],
    "transformIgnorePatterns": [
      "node_modules/(?!((jest-)?react-native|react-clone-referenced-element|react-navigation|react-native-router-flux))"
    ]
  },
  // ...
}

({“Object.<anonymous>”:function(module,exports,require,__dirname,__filename,global,jest){�PNG

None of the above answers has solved my problem

While the solution by @mbaranovski works, I don’t know if his intention was to use it as a transformer. It produces the following output (pay attention to the src attribute):

<img alt="ImgName" height="28" src={ Object { "process": [Function], } } width="112" />

Essentially, it is mapping everything from that module to the place where I required an SVG. Thus, you could get away with that module simply being:

module.exports = {}

The other work-around as stated above is to use identity-obj-proxy.

I had this png problem after adding ./node_modules/react-native-gesture-handler/jestSetup.js to setupFiles (that was my attempt to resolve the jest issue with react-native-gesture-handler).

I tried https://github.com/facebook/jest/issues/2663#issuecomment-341384494 (@magnusart using identity-obj-proxy), but it broke enzyme for whatever reason (it made enzyme’s mock into a symbol rather than a function). Then I tried https://github.com/facebook/jest/issues/2663#issuecomment-369040789 (@eddyerburgh using jest-transform-stub), but it didn’t do anything.

Eventually, I tried https://github.com/facebook/jest/issues/2663#issuecomment-274270387 (@cpojer the webpack solution at the beginning), and that was the only one working for me.

@magnusart
you save my day, it works fine

Errors like this may also be a result of using a preset with absolute paths set in module name mapper for example. This case however will be fixed in the next release