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 · 29 comments

Comments

@matheusml
Copy link

@matheusml matheusml commented Jan 21, 2017

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

This comment has been minimized.

Copy link
Contributor

@cpojer cpojer commented Jan 21, 2017

@cpojer cpojer closed this Jan 21, 2017
@twgraham

This comment has been minimized.

Copy link

@twgraham 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

This comment has been minimized.

Copy link

@zeeshanjan82 zeeshanjan82 commented Mar 12, 2017

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

@zeeshanjan82

This comment has been minimized.

Copy link

@zeeshanjan82 zeeshanjan82 commented Mar 12, 2017

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

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

@sibinx7

This comment has been minimized.

Copy link

@sibinx7 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

This comment has been minimized.

Copy link

@JeffreyLeeSpokeo JeffreyLeeSpokeo commented Jun 7, 2017

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

This comment has been minimized.

Copy link

@diegomura diegomura commented Jun 27, 2017

Same error as well. Does someone fix it?

@Elf2707

This comment has been minimized.

Copy link

@Elf2707 Elf2707 commented Jul 7, 2017

Have the same error with .mp3, Nothing helps

@thymikee

This comment has been minimized.

Copy link
Collaborator

@thymikee 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

This comment has been minimized.

Copy link

@mbaranovski mbaranovski commented Jul 21, 2017

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

This comment has been minimized.

Copy link

@alecmerdler alecmerdler commented Aug 31, 2017

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

facebook/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

This comment has been minimized.

Copy link

@alp82 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

This comment has been minimized.

Copy link

@alp82 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

This comment has been minimized.

Copy link

@alp82 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

This comment has been minimized.

Copy link

@timgivois timgivois commented Oct 31, 2017

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

This comment has been minimized.

Copy link

@magnusart magnusart commented Nov 2, 2017

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

This comment has been minimized.

Copy link

@theoutlander theoutlander commented Nov 15, 2017

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

This comment has been minimized.

Copy link

@ashishjan 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

This comment has been minimized.

Copy link

@wellyal 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

This comment has been minimized.

Copy link
Collaborator

@SimenB 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

This comment has been minimized.

Copy link
Contributor

@eddyerburgh eddyerburgh commented Feb 27, 2018

Another workaround:

npm i --save-dev jest-transform-stub
"jest": {
  "transform": {
    ".+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$": "jest-transform-stub"
  }
}
yukihirop added a commit to yukihirop/onepage that referenced this issue Mar 3, 2018
この設定が無いとこのようなエラーが起きる
```
console.error node_modules/vue/dist/vue.runtime.common.js:1715
    /Users/fukudayukihiro/RubymineProjects/onepage/frontend/src/assets/home/user/aimerald.png:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){�PNG
                                                                                             ^

    SyntaxError: Invalid or unexpected token
        at ScriptTransformer._transformAndBuildScript (/Users/fukudayukihiro/RubymineProjects/onepage/frontend/node_modules/jest-runtime/build/script_transformer.js:307:17)
        at ScriptTransformer.transform (/Users/fukudayukihiro/RubymineProjects/onepage/frontend/node_modules/jest-runtime/build/script_transformer.js:341:19)
        at Runtime._execModule (/Users/fukudayukihiro/RubymineProjects/onepage/frontend/node_modules/jest-runtime/build/index.js:525:53)
        at Runtime.requireModule (/Users/fukudayukihiro/RubymineProjects/onepage/frontend/node_modules/jest-runtime/build/index.js:329:14)
        at Runtime.requireModuleOrMock (/Users/fukudayukihiro/RubymineProjects/onepage/frontend/node_modules/jest-runtime/build/index.js:409:19)
        at Object.data (/Users/fukudayukihiro/RubymineProjects/onepage/frontend/src/components/__test__/factories/users.js:5:7)
        at VueComponent.data (/Users/fukudayukihiro/RubymineProjects/onepage/frontend/src/components/__test__/organisms/mdedia_object/UserMedia.spec.js:15:37)
        at VueComponent.mergedInstanceDataFn (/Users/fukudayukihiro/RubymineProjects/onepage/frontend/node_modules/vue/dist/vue.runtime.common.js:1159:20)
        at getData (/Users/fukudayukihiro/RubymineProjects/onepage/frontend/node_modules/vue/dist/vue.runtime.common.js:3384:17)
        at initData (/Users/fukudayukihiro/RubymineProjects/onepage/frontend/node_modules/vue/dist/vue.runtime.common.js:3343:7)
```

参考
facebook/jest#2663 (comment)
@solomontang solomontang referenced this issue May 18, 2018
@gengjiawen

This comment has been minimized.

Copy link
Contributor

@gengjiawen gengjiawen commented May 24, 2018

I have a react native module has images. I have tried assetsTransformer, identity-obj-proxy and jest-transform-stub. Only assetsTransformer works.

@hanpanpan200

This comment has been minimized.

Copy link

@hanpanpan200 hanpanpan200 commented Jun 20, 2018

Hi @sibinx7 I fixed that issue by: #2663

@FibreFoX

This comment has been minimized.

Copy link

@FibreFoX FibreFoX commented Jul 26, 2018

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))"
    ]
  },
  // ...
}
@harps116

This comment has been minimized.

Copy link

@harps116 harps116 commented Sep 12, 2018

Slight modification for handling xml files, in this case using the transform option:

jest.config.js

module.exports = {
    transform: {
        ".+.(xml|bpmn)": "<rootDir>/src/__tests__/transformers/xmlTransformer.ts"
    },
}

/src/tests/transformers/xmlTransformer.ts ( may need to modify to your path, is a helper that represents the root directory of the project ).

module.exports = {
    process() {
        return 'module.exports = {};';
    },
    getCacheKey() {
        // The output is always the same.
        return 'xmlTransform';
    },
};

See here for more details.

@riyajk

This comment has been minimized.

Copy link

@riyajk riyajk commented Dec 2, 2018

@rickhanlonii

This comment has been minimized.

Copy link
Member

@rickhanlonii rickhanlonii commented Dec 2, 2018

@vic3king

This comment has been minimized.

Copy link

@vic3king vic3king commented Apr 19, 2019

@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

This comment has been minimized.

Copy link

@yyynnn yyynnn commented Jul 1, 2019

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)

facebook/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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
You can’t perform that action at this time.