2

I am using create-react-app. Running jest from the CLI causes this error (though in VS Code it shows in my test file that my test passes):

(base) ➜  component-library git:(setup) ✗ jest
 FAIL  src/App.test.js
  ● Test suite failed to run

    Jest encountered an unexpected token

    This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.

    By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".

    Here's what you can do:
     • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/en/ecmascript-modules for how to enable it.
     • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
     • If you need a custom transformation specify a "transform" option in your config.
     • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

    You'll find more details and examples of these config options in the docs:
    https://jestjs.io/docs/en/configuration.html

    Details:

    /Users/Me/go/src/gitlab.com/tensile-payments/component-library/src/setupTests.js:5
    import '@testing-library/jest-dom';
    ^^^^^^

    SyntaxError: Cannot use import statement outside a module

      at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1350:14)

My setupTests.js file looks like this:

// jest-dom adds custom jest matchers for asserting on DOM nodes.
// allows you to do things like:
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
import '@testing-library/jest-dom';
import Enzyme from 'enzyme';
import Adapter from '@wojtekmaj/enzyme-adapter-react-17';

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

I understand from another question's answer that Jest Babel-transforms files before running tests, which should get rid of these import statements. I haven't ejected and so haven't changed the babel config. Other people had the issue that node modules weren't being transformed because the default config excludes them, but this error isn't coming from a node module. How can I fix this?

1 Answer 1

0

I fixed it by running tests with npm run test instead of jest, as well as removing

  "jest": {
    "setupFilesAfterEnv": [
      "<rootDir>src/setupTests.js"
    ]
  }

from my package.json (though Enzyme instructs to include it when using Jest).

Sign up to request clarification or add additional context in comments.

1 Comment

Enzyme is dead. You should try to migrate to RTL

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.