Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

"Syntax Error: Invalid or unexpected token" with .png #2663

Closed
matheusml opened this issue Jan 21, 2017 · 36 comments
Closed

"Syntax Error: Invalid or unexpected token" with .png #2663

matheusml opened this issue Jan 21, 2017 · 36 comments

Comments

@matheusml
Copy link

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!

@cpojer
Copy link
Member

cpojer commented Jan 21, 2017

Check out http://facebook.github.io/jest/docs/tutorial-webpack.html#content

EDIT: new link is https://jestjs.io/docs/en/webpack

@cpojer cpojer closed this as completed Jan 21, 2017
@twgraham
Copy link

twgraham commented Feb 9, 2017

@matheusml did you solve this at all? @cpojer I can confirm I'm having this issue too. I have static assets outside my source. i.e. My directory structure looks like:

public
|-fonts
|-img
\_styles
src
|-components
|-pages
...

My jest config looks similar to the example given in the link:

"jest": {
    "collectCoverageFrom": [ "src/**/*.{js,jsx}" ],
    "moduleNameMapper": {
      "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "tests/__mocks__/fileMock.js"
    }
  }

My test fails when it tries to import the image:

import thumbnail from 'img/thumbnail.png'

I guess its important to note that if I don't include the public directory in moduleDirectories, then i get the error: Cannot find module 'img/thumbnail.png' from 'MyModule.js'

Is this expected? Should it really validate the existence of an import event though the module mapping is already setup? Otherwise I get the same error as above. I haven't tried any other type of import in the name mapper.

@zeeshanjan82
Copy link

I am facing the same issue, I am trying to have reactjs server rendering implemented. Any fix for this.

@zeeshanjan82
Copy link

zeeshanjan82 commented Mar 12, 2017

I have put this in my babelrc and things seem to be working:

{
"presets": ["es2015", "react"]
}

@sibinx7
Copy link

sibinx7 commented Jun 1, 2017

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 <

@JeffreyLeeSpokeo
Copy link

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

@diegomura
Copy link

Same error as well. Does someone fix it?

@Elf2707
Copy link

Elf2707 commented Jul 7, 2017

Have the same error with .mp3, Nothing helps

@thymikee
Copy link
Collaborator

thymikee commented Jul 7, 2017

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

@mbaranovski
Copy link

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

@alecmerdler
Copy link

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.

coryhouse pushed a commit to coryhouse/react-slingshot that referenced this issue Sep 3, 2017
* removed react-router form package.json & installed react-router-dom.

* completed index.src refactor.

* re-implemented App.js

* added notes to import changes & App.js

* modified middleware array @ store/configureStore.js

* updated yarn.lock file with fresh `yarn` command.

* updated master branch.

* upgraded react-hot-reloader to @3.0.0-beta.6

* removed extra "document.getElementById(app) from Root.js

* moved react-router-redux to regular "dependencies" from "dev-dependencies"

* cleaned Root.propTypes.

* cleaned Root.js & App.js per @oshalygin feedback.

* replaced .gitignore comment.

* removed react-router form package.json & installed react-router-dom.

* completed index.src refactor.

* re-implemented App.js

* added notes to import changes & App.js

* Update FAQ.md

fixed header on FAQ page

* Update README.md

fixed a few headers improperly declared

* modified middleware array @ store/configureStore.js

* Add react hot loader 3 (#392)

- This commit wires up react-hot-loader 3 to
  be used in the application.  There are numerous
  benefits to the latest release, all of which
  can be seen at https://github.com/gaearon/react-hot-loader
- Note that the specific implementation around
  wrapping in a Root component is part of how
  react-hot-loader 3 needs to be configured.
- Note that the package is brought in as a
  dependency, not a dev dependency because of
  how it is switched at runtime or not.
- More information on the migration can be
  viewed at:
https://github.com/gaearon/react-hot-loader/tree/master/docs\#migration-to-30

Related: #216

* Updated react-hot-loader to correct package version. (#401)

* Add item to check if issues

* updated yarn.lock file with fresh `yarn` command.

* Fix formatting (#403)

* updated master branch.

* upgraded react-hot-reloader to @3.0.0-beta.6

* removed extra "document.getElementById(app) from Root.js

* moved react-router-redux to regular "dependencies" from "dev-dependencies"

* cleaned Root.js & App.js per @oshalygin feedback.

* replaced .gitignore comment.

* clean index.js

* Add CONTRIBUTE.md (#431)

* Add

* Updated yarn lock using upgrade

* Rename

* Update

* Upgrade to webpack 3

* Update yarn lock

* Update snapshot

* Set prod env when analyzing bundle

* Add jest-cli as dependency

* Revert PR #450 (#451)

Removed change that removed additional dashes in npm test scripts in favor of adding jest-cli as a devDep.

This commit instead focusses on issue 2 from #449 where setupPrompts.js had a bug that caused start script to fail.

* Issue #449 fix (#450)

* Issue #449 fix

Issue 1:
Removed extra dashes located in the package.json test scripts that cause start script to fail.

Issue 2:
Removed escape characters found in setupPrompts.js which cause linting to fail, thus breaking start script.

* Jest fix

Re-added previously removed dashes from test scripts in package.json that caused start script to fail. Instead, @coryhouse added in jest-cli as a dev-dep which resolves the issue.

* Enhance babel env config to transpile for IE9+ (#452)

* Fix for jest handling of static assets when running tests. See: (#457)

jestjs/jest#2663 (comment)

* Added tips for npm run lint and build errors (#151) (#460)

* pushing changes from upstream fetch.

* updated from rebase.

* modified package versions in package.json & created new build.

* update package.json

* fixed conflicts with upstream master.

* cleaned up PropTypes validations - react-router-redux throwing PropTypes error.

* comment spell check & de-console on Root.js
@alp82
Copy link

alp82 commented Oct 29, 2017

I added the assetTransformer.js mentioned by @bombellos. Also followed instructions on Using with webpack. But i still get the same errors.

PNG:

 FAIL  components/__tests__/List.js
  ● Test suite failed to run

    /assets/images/logo-header.png:1
    ({"Object.<anonymous>":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)
      at Object.<anonymous> (components/PageHeader.js:15:19)
      at Object.<anonymous> (components/Main.js:10:436)

SVG:

 FAIL  ui/Button/__tests__/snapshot.test.js
  ● fixture 'TextAndIcon' snapshots are rendered correctly

    /assets/icons/fontawesome/regular.svg:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){<svg xmlns="http://www.w3.org/2000/svg" style="display: none;">
                                                                                             ^
    
    SyntaxError: Unexpected token <
      
      at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:305:17)
      at Icon (ui/Icon.js:31:17)
      at resolve (node_modules/react-dom/cjs/react-dom-server.node.development.js:2599:14)
      at ReactDOMServerRenderer.render (node_modules/react-dom/cjs/react-dom-server.node.development.js:2746:22)
      at ReactDOMServerRenderer.read (node_modules/react-dom/cjs/react-dom-server.node.development.js:2722:19)
      at Object.renderToStaticMarkup (node_modules/react-dom/cjs/react-dom-server.node.development.js:2991:25)

My folder structure is basically:

<rootDir>
  assets
    *.png, *.svg, ...
  components
    *.js
  ui
    *.js

Apparently, the files are still loaded instead of mocked away, but i have no clue how to debug this.

.babelrc:

{
  "presets": [
    ["es2015", {"modules": false}],
    "react",
    "stage-1",
    ["env", {
      "targets": {
        "browsers": [
          "last 3 versions",
          "> 1%",
          "Firefox ESR",
          "iOS 9"
        ]
      }
    }]
    
  ],
  "plugins": [
    "react-hot-loader/babel",
    "transform-class-properties",
    "transform-react-jsx-source",
    "glamorous-displayname",
    "wildcard"
  ],
  "env": {
    "development": {
      "plugins": [
        ["transform-runtime", {
          "polyfill": true
        }]
      ]
    },
    "test": {
      "plugins": ["transform-es2015-modules-commonjs"]
    }
  }
}

package.json:

  "jest": {
    "snapshotSerializers": [
      "jest-glamor-react",
      "enzyme-to-json/serializer"
    ],
    "moduleFileExtensions": ["js"],
    "moduleDirectories": ["node_modules"],
    "transform": {
      "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/config/jest/assetsTransformer.js"
    }
  },

@alp82
Copy link

alp82 commented Oct 29, 2017

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.

@alp82
Copy link

alp82 commented Oct 29, 2017

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.

@timgivois
Copy link

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"
    },

@magnusart
Copy link

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"
    }
  }

@theoutlander
Copy link

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.

@ashishjan
Copy link

ashishjan commented Feb 1, 2018

@magnusart

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

it saves my day. Thanks!!.

@wellyal
Copy link

wellyal commented Feb 5, 2018

@mbaranovski It worked just fine when I ran only jest for test. Sadly when I try to run through the react-scripts from create-react-app I get

Out of the box, Create React App only supports overriding these Jest options

Is there a workaround for this ? Or the only solution is to eject create-react-app?

@SimenB
Copy link
Member

SimenB commented Feb 5, 2018

I don't think CRA supports that option. I'm not sure why it wants to close down options, probably a good reason 🙂

/cc @gaearon

@eddyerburgh
Copy link
Contributor

Another workaround:

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

@riyajk
Copy link

riyajk commented Dec 2, 2018

Check out http://facebook.github.io/jest/docs/tutorial-webpack.html#content

The given link is broken

@rickhanlonii
Copy link
Member

https://jestjs.io/docs/en/webpack

@vic3king
Copy link

@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

@yyynnn
Copy link

yyynnn commented Jul 1, 2019

or use this https://github.com/eddyerburgh/jest-transform-stub

newsum2019 added a commit to newsum2019/singleshot that referenced this issue Oct 6, 2019
* removed react-router form package.json & installed react-router-dom.

* completed index.src refactor.

* re-implemented App.js

* added notes to import changes & App.js

* modified middleware array @ store/configureStore.js

* updated yarn.lock file with fresh `yarn` command.

* updated master branch.

* upgraded react-hot-reloader to @3.0.0-beta.6

* removed extra "document.getElementById(app) from Root.js

* moved react-router-redux to regular "dependencies" from "dev-dependencies"

* cleaned Root.propTypes.

* cleaned Root.js & App.js per @oshalygin feedback.

* replaced .gitignore comment.

* removed react-router form package.json & installed react-router-dom.

* completed index.src refactor.

* re-implemented App.js

* added notes to import changes & App.js

* Update FAQ.md

fixed header on FAQ page

* Update README.md

fixed a few headers improperly declared

* modified middleware array @ store/configureStore.js

* Add react hot loader 3 (#392)

- This commit wires up react-hot-loader 3 to
  be used in the application.  There are numerous
  benefits to the latest release, all of which
  can be seen at https://github.com/gaearon/react-hot-loader
- Note that the specific implementation around
  wrapping in a Root component is part of how
  react-hot-loader 3 needs to be configured.
- Note that the package is brought in as a
  dependency, not a dev dependency because of
  how it is switched at runtime or not.
- More information on the migration can be
  viewed at:
https://github.com/gaearon/react-hot-loader/tree/master/docs\#migration-to-30

Related: #216

* Updated react-hot-loader to correct package version. (#401)

* Add item to check if issues

* updated yarn.lock file with fresh `yarn` command.

* Fix formatting (#403)

* updated master branch.

* upgraded react-hot-reloader to @3.0.0-beta.6

* removed extra "document.getElementById(app) from Root.js

* moved react-router-redux to regular "dependencies" from "dev-dependencies"

* cleaned Root.js & App.js per @oshalygin feedback.

* replaced .gitignore comment.

* clean index.js

* Add CONTRIBUTE.md (#431)

* Add

* Updated yarn lock using upgrade

* Rename

* Update

* Upgrade to webpack 3

* Update yarn lock

* Update snapshot

* Set prod env when analyzing bundle

* Add jest-cli as dependency

* Revert PR #450 (#451)

Removed change that removed additional dashes in npm test scripts in favor of adding jest-cli as a devDep.

This commit instead focusses on issue 2 from #449 where setupPrompts.js had a bug that caused start script to fail.

* Issue #449 fix (#450)

* Issue #449 fix

Issue 1:
Removed extra dashes located in the package.json test scripts that cause start script to fail.

Issue 2:
Removed escape characters found in setupPrompts.js which cause linting to fail, thus breaking start script.

* Jest fix

Re-added previously removed dashes from test scripts in package.json that caused start script to fail. Instead, @coryhouse added in jest-cli as a dev-dep which resolves the issue.

* Enhance babel env config to transpile for IE9+ (#452)

* Fix for jest handling of static assets when running tests. See: (#457)

jestjs/jest#2663 (comment)

* Added tips for npm run lint and build errors (#151) (#460)

* pushing changes from upstream fetch.

* updated from rebase.

* modified package versions in package.json & created new build.

* update package.json

* fixed conflicts with upstream master.

* cleaned up PropTypes validations - react-router-redux throwing PropTypes error.

* comment spell check & de-console on Root.js
@begueradj
Copy link

begueradj commented Jan 2, 2020

only @eddyerburgh 's solution worked for me.

@guilleanto22
Copy link

@magnusart
you save my day, it works fine

@FanchenBao
Copy link

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 #2663 (comment) (@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 #2663 (comment) (@eddyerburgh
using jest-transform-stub), but it didn't do anything.

Eventually, I tried #2663 (comment) (@cpojer the webpack solution at the beginning), and that was the only one working for me.

@gus-messagi
Copy link

If anyone is getting this error with SVG, probably can use this lib, it worked really well for me https://www.npmjs.com/package/jest-svg-transformer

I only added on my jest.config.ts file this code

transform: { '^.+\\.tsx?$': 'babel-jest', '^.+\\.svg$': 'jest-svg-transformer', },

And the code on this file is this
Captura de Tela 2020-11-09 às 13 17 01

you guys can ignore moduleNameMapper, is just because I'm using custom import with babel

dididy pushed a commit to Yapp-17th/Web_2_Client that referenced this issue Nov 12, 2020
dididy pushed a commit to Yapp-17th/Web_2_Client that referenced this issue Nov 12, 2020
@sabun123
Copy link

sabun123 commented Dec 3, 2020

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.

@equicy
Copy link

equicy commented May 10, 2021

({"Object.":function(module,exports,require,__dirname,__filename,global,jest){�PNG

None of the above answers has solved my problem

@github-actions
Copy link

This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.
Please note this issue tracker is not a help forum. We recommend using StackOverflow or our discord channel for questions.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators Jun 10, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests